Python Strings

In a previous article, we discussed several Python data types - int, float, str, etc.

One of the most used data types is a string. It has made text very easy to deal with in Python.

String

It is nothing but a sequence of characters. The length of the sequence can be 0 or greater. A string of length 0 and 1 are generally called empty string and a character respectively.

You can declare string in multiple ways -

Single quotes

x = ''
x = 'a'
x = 'Delhi'
x = '"War and Peace" was written by Leo Tolstoy'

Double quotes

x = ""
x = "a"
x = "What's your name"

Triple quotes

It is mostly used in the docstring and multi-line string. But you can also use this if your text contains both single and double quote characters. Like:

multi_line_string = """There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult. - C.A.R. Hoare
"""

example = """Do you agree with the saying, "All's fair in love and war"?"""

 

Now, we'll see several operations that can be performed on strings. One thing that you should keep in mind is -- string is nothing but an immutable array(list) of characters. This is the reason you'll see why they behave similarly in many cases.

Length of a string

x = "Python Tutorials"
print(len(x))
# 16

x = ''
print(len(x))
# 0

Indexing

It is useful in accessing the character from the start of a string at a given index. The index in Python begins at 0. So index 0, represents the first character and so on.

x = "Python Tutorials"
print("Character at index 0: ", x[0], "\n", "Character at index 1: ",x[1])
Character at index 0:  P 
Character at index 1:  y

Negative Indexing

Sometimes you'd like to access characters from the end of a string. Negative indexing is just syntactic sugar for that.

x = "New Delhi"
print("Last character: ", x[len(x)-1])
# or you can use
print("Last character: ", x[-1])

Slicing

It is useful when we want to get substring using the range. The syntax for it is: string[start:stop:step]

x = "New Delhi is the capital of India."
# start - 4, end - 9
print(x[4:9])

There are a lot of other methods, like - islower(), strip(), format()  that can be performed on the string, which we'll discuss in the next article.

Happy Coding. Never Stop Hacking!!

0 Comments

Join discussion:

Login