Good day, learners. In this tutorial we are going to learn Python String. In our previous tutorial we learned about Python Tuple.
Table of Contents
One of the most common data type of python is String. “str” is the built in string class of python. String literals can be enclosed by single or double quotes. You can see some example of string literals below
literal1 = "This is the first literal" literal2 = "This is the second literal"
Accessing the Python String
You can print the whole string or a specific portion of the string which is called substring. To do so, you need to know some basics. The Python Strings are indexed from zero. That means if the size of the string is 5, the index of the elements are 0 to 4. The following code will help you to understand the context
word = "Tobacco" #index: 0123456 #This will print the whole word print(word) #Tobacco #This will print the size of the string print(len(word)) #7 #This will print the 0th element of the string which is T print(word) #T #prints the 1st element (o) to 4th element (c) of the string print(word[1:5]) #obac #prints the substring from 3rd element to the end of the string print(word[3:]) #acco #prints from the 0th element to 2nd element of the string print(word[:3]) #Tob
The output of the following code will be
================== RESTART: /home/imtiaz/str.py ================== Tobacco 7 T obac acco Tob
Concatenating the python string
You can concat two string by simply placing a “+” operator between them. You can concat a number with the string, but the condition is you have to change the number to a string. You can use str() function to convert a number to string. The following example will give you some idea about this
str1 = "I love" str2 = "I hate" str3 = " you!" #example of concatenation between two string print(str1 + str3) #this will give an error #print("My age is "+15) #after converting the number to a string, concatenate it with a string print("My age is "+str(15))
The output of the following code will be
Updating Python String
Python string does not allow to update element of the string. However, you can try slicing technique, to create a new string withe updated specific index of the string. Suppose, we have a word “toek”, but we want to make it “took”. Now, look at the word, the element “e” that needs to be updated is at index 2. So we can slice the substrings before and after “e”, those are “to” and “k” respectively. Then we can concatenate “to” with the updated element “o” and after that we can concatenate the resultant string with “k”. So the code will illustrate the idea
str1 = 'toek' print("Before Update:") print(str1) first = str1[:2] #that is 'to' update = 'o' last = str1[3:] #that is 'k' str1 = first + update + last print("After Update:") print(str1)
The output will be
================== RESTART: /home/imtiaz/str3.py ================== Before Update: toek After Update: took >>>
Python String Methods
There are some methods to manipulate Python String. You can find all the python string method to their official here. Most common python string methods are shown below:
- lower(): returns the lowercase version of the string
- upper(): returns the uppercase version of the string
- strip(): returns a string with whitespace removed from the start and end
- isalnum(): return true if all characters in the string are alphanumeric and there is at least one character, false otherwise.
- isalpha(): return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
- title(): return a title-cased version of the string where words start with an uppercase character and the remaining characters are lowercase.
- join(list): joins the elements in the given list together using the string as the delimiter
- find(substring): returns the lowest index in the string where substring is found. If substring is not found, it returns -1.
Escape Sequence with Python String
You can put escape sequence in string literal to perform some special task. Suppose, you have two words “cat” and “dog”. You want to put them in one string literal but want then in separate line. To do so, you can add ‘\n’ between these two words. The following example will help you to understand.
task = 'cat\ndog' print(task)
The output will print ‘cat’ and ‘dog’ in separate line. There are some escape sequences. If you’re interested, you can find it here
Python String contains
If you want to check if a substring is present in a string or not, then we can use in operator as shown in below example.
str1 = "I am here" if "I" in str1: print("Found") else: print("Not Found")
Python String split
Sometimes we get a long string with delimiter and we want to split them into a list. For example it’s most common in CSV data. We can use string split function for this.
x = "1,2,3" y = x.split(",") print(y)
It will print below output.
>>> ================= RESTART: /Users/pankaj/Desktop/string1.py ================= ['1', '2', '3'] >>>
So, this is all about basic Python String. Hope that you understood well. If you have any query regarding Python String, feel free to ask in the comment section.