Strings in Python with examples

Spread the love

A string represents a group of characters. Strings are important because most of the data that we use in daily life will be in the form of strings. For example the name of a person, their addresses, their vehicle numbers etc. are all strings.

Creating Strings in python –

We can create a string in Python by assigning a group of characters to a variable. The group of characters should be enclosed inside single quotes or double quotes as

In [1]: s1 = 'I love Python'

In [2]: s2 = "I love Python"

There is no difference between the single quotes or double quotes while creating the strings. Both will work in the same manner.

Sometimes, we can use triple single quotes or triple double quotes to represent strings. These quotation marks are useful when we want to represent a string that occupies several lines.

In [3]: s3 = '''I'm fine without you now
   ...: I don't need you here
   ...: I'm fine without you now
   ...: can you disappear?'''

In the above code we used triple single quotes, we can also use triple double quotes as shown below.

In [5]: s4 = """I'm fine without you now
   ...: I don't need you here
   ...: I'm fine without you now
   ...: can you disappear?"""

Finding Length of a String –

The Length of a string represents the number of characters in a string. To know the length of a string we can use the len() function. This function gives the number of characters including spaces in the string.

In [6]: s5 = 'Python'

In [7]: length = len(s5)

In [8]: print(length)

Indexing in Strings –

Index represents the position number. Index is written using square braces []. By specifying the position number through an index, we can refer to the individual elements (or characters) of a string. For example str[0] refers to the 0th element of the string and str[1] refers to the 1st element of the string. Thus str[i] can be used to refer to ith element of the string. Here i is called the string index because it is specifying the position number of element in the string.

In [10]: string = 'Python'

In [11]: string[0]
Out[11]: 'P'

In [12]: string[2]
Out[12]: 't'

When we use index as a negative number, it refers to elements in the reverse order. Thus, str[-1] refers to the last element and str[-2] refers to second element from last.

In [14]: string = 'Python'

In [15]: string[-1]
Out[15]: 'n'

In [16]: string[-2]
Out[16]: 'o'

Slicing the strings in Python –

A slice represents a part or piece of a string. The format of slicing is

string[start: stop: stepsize]

if start and stop are not specified, then slicing is done from 0th to n-1th element. If stepsize is not written then it is taken to be 1.

In [17]: str = 'I Love Python'

In [18]: # access string from 0th to 8th element in step of 1

In [19]: str[0:9:1]
Out[19]: 'I Love Py'

When stepsize is 2, then it will access every other characters from 1st character onward. Hence it retrieves the 0th, 2nd, 4th, 6th characters and so on.

In [20]: str[0:9:2]
Out[20]: 'ILv y'

Some other examples given below to have a better understanding on slicing.

In [21]: # access string from 0th to last character

In [22]: str[::]
Out[22]: 'I Love Python'

In [23]: # access from str[2] to str[3] in step of 1

In [24]: str[2:4:1]
Out[24]: 'Lo'

In [25]: # access entire string in step of 2

In [26]: str[::2]
Out[26]: 'ILv yhn'

In [27]: # access string from str[2] to ending

In [28]: str[2::]
Out[28]: 'Love Python'

In [29]: # access from str[-4] to str[-2] from left to right

In [30]: str[-4:-1]
Out[30]: 'tho'

In [31]: # access from str[-6] till the end of the string

In [32]: str[-6::]
Out[32]: 'Python'

In [33]: # retrieve from str[-1] to str[-3] from right to left

In [34]: str[-1:-4:-1]
Out[34]: 'noh'

In [35]: # retrive from str[-1] till first element from right to left

In [36]: str[-1::-1]
Out[36]: 'nohtyP evoL I'

In [37]: 

Repeating the strings in Python –

The repetition operator is denoted by asterisk ( * ) symbol and useful to repeat the string for several times. For example str * n repeats the string for n times.

In [37]: str = 'python'

In [38]: str * 2
Out[38]: 'pythonpython'

Similarly, it is possible to repeat a part of the string obtained by slicing as

In [39]: str[2:4] * 3
Out[39]: 'ththth'

Concatenation of String in Python –

We can use + on strings to join a string at the end of another string. This operator + is called addition operator when used on numbers. But when used on strings, it is called concatenation operator since it joins or concatenates the strings. Similar result can be achieved using the join() method which will be discussed later.

In [40]: s1 = 'I '

In [41]: s2 = 'Love '

In [42]: s3 = 'Python'

In [43]: s1 + s2 + s3
Out[43]: 'I Love Python'

in and not in Operators –

in and not in operators can be used with strings to determine whether a string is present in another string. Therefore the in and not in operator are also known as membership operators.

str1 = 'I Love Python'
str2 = 'Love'
if str2 in str1:
    print('Not Found')
str1 = 'Python is awesome'
str2 = 'Love'
if str2 not in str1:
    print("str2 not in Str1")
    print("str2 in str1")
str2 not in Str1

You can also use the in and not in operator to check whether a character is present in a word.

In [48]: 'p' in 'python'
Out[48]: True

In [49]: 'p' not in 'python'
Out[49]: False

Comparing Strings in Python –

We can use the relational operators like >, >=, < , <=, ==, != operators to compare two strings. They return Boolean value i.e. either True or False depending on the strings being compared.

s1 = 'Python'
s2 = 'Cython'
if (s1 == s2):
    print('Both are same')
    print('Not same')
Not same

This code return Not same as the strings are not same. While comparing the strings, Python interpreter compares them by taking them in English dictionary order. The string which comes comes first in the dictionary order will have a low value than the string which comes next. It means A is less than B which is less than C and so on.

if s1 < s2:
    print('s1 less than s2')
    print('S1 greater than or equal to s2')
S1 greater than or equal to s2

Removing Spaces from a String in Python –

A space is also considered as a character inside a string. Sometimes the unnecessary spaces in a string will lead to wrong results. For example, take a look at the below code.

if 'Python  ' == 'Python':
    print("Not Same")
Not Same

The output of the above code is Not same as there are few extra white spaces in the first string. Hence such spaces should be removed from the strings before they are compared. This is possible using rstrip(), lstrip() and strip() methods. The rstrip() method removes the spaces which are at the right side of the string. The lstrip() method removes spaces which are at the left side of the string. strip() method removes spaces from both the sides of the strings. These methods do not removes spaces which are in the middle of the string.

In [55]: string = '  Python  '

In [56]: string.lstrip()
Out[56]: 'Python  '

In [57]: string.rstrip()
Out[57]: '  Python'

In [58]: string.strip()
Out[58]: 'Python'

Replace a String with another String in Python –

The replace() method is useful to replace a sub string in a string with another sub string. The syntax of using this method is

string.replace(old, new)

This will replace all the occurrences of old sub string with new sub string in the main string.

In [59]: string = 'python'

In [60]: string.replace('p', 'c')
Out[60]: 'cython'

Changing Case of a String in Python –

Python offers 4 methods that are useful to change the case of a string. They are upper(), lower(), swapcase(), title(). The upper() method is used to convert all the characters of a string into uppercase or capital letters. The lower() method converts the string into lowercase or into small letters. The swapcase() method converts the uppercase letters into lowercase letters and vice versa. The title() method converts the string such that each word in the string will start with a uppercase letter and remaining will be lowercase letters.

In [61]: string = 'Python is awesome'

In [62]: string.lower()
Out[62]: 'python is awesome'

In [63]: string.upper()

In [64]: string.swapcase()

In [65]: string.title()
Out[65]: 'Python Is Awesome'

Checking Starting and Ending of a String in Python –

The startswith() method is useful to know whether a string is starting with a sub string or not. The way to use this method is


When the sub string is found in the main string, this method returns True. If the sub string is not found, it returns False.

In [66]: string = 'python is awesome'

In [67]: string.startswith('python')
Out[67]: True

Similarly to check the ending of a string, we can use endswith() method. It returns True if the string ends with the specified sub string otherwise returns False.

In [68]: string.endswith('awesome')
Out[68]: True

Rating: 1 out of 5.

Leave a Reply