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 : s1 = 'I love Python' In : 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 : 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 : 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 : s5 = 'Python' In : length = len(s5) In : print(length) 6
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 refers to the 0th element of the string and str 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 : string = 'Python' In : string Out: 'P' In : string Out: '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 : string = 'Python' In : string[-1] Out: 'n' In : string[-2] Out: '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 : str = 'I Love Python' In : # access string from 0th to 8th element in step of 1 In : str[0:9:1] Out: '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 : str[0:9:2] Out: 'ILv y'
Some other examples given below to have a better understanding on slicing.
In : # access string from 0th to last character In : str[::] Out: 'I Love Python' In : # access from str to str in step of 1 In : str[2:4:1] Out: 'Lo' In : # access entire string in step of 2 In : str[::2] Out: 'ILv yhn' In : # access string from str to ending In : str[2::] Out: 'Love Python' In : # access from str[-4] to str[-2] from left to right In : str[-4:-1] Out: 'tho' In : # access from str[-6] till the end of the string In : str[-6::] Out: 'Python' In : # retrieve from str[-1] to str[-3] from right to left In : str[-1:-4:-1] Out: 'noh' In : # retrive from str[-1] till first element from right to left In : str[-1::-1] Out: 'nohtyP evoL I' In :
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 : str = 'python' In : str * 2 Out: 'pythonpython'
Similarly, it is possible to repeat a part of the string obtained by slicing as
In : str[2:4] * 3 Out: '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 : s1 = 'I ' In : s2 = 'Love ' In : s3 = 'Python' In : s1 + s2 + s3 Out: '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('Found') else: print('Not Found')
str1 = 'Python is awesome' str2 = 'Love' if str2 not in str1: print("str2 not in Str1") else: print("str2 in str1")
#output 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 : 'p' in 'python' Out: True In : 'p' not in 'python' Out: 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') else: print('Not same')
#output 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') else: print('S1 greater than or equal to s2')
#output 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('Same') else: print("Not Same")
#output 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 : string = ' Python ' In : string.lstrip() Out: 'Python ' In : string.rstrip() Out: ' Python' In : string.strip() Out: '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
This will replace all the occurrences of old sub string with new sub string in the main string.
In : string = 'python' In : string.replace('p', 'c') Out: '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 : string = 'Python is awesome' In : string.lower() Out: 'python is awesome' In : string.upper() Out: 'PYTHON IS AWESOME' In : string.swapcase() Out: 'pYTHON IS AWESOME' In : string.title() Out: '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 : string = 'python is awesome' In : string.startswith('python') Out: 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 : string.endswith('awesome') Out: True