Strings in Python
FREE Online Courses: Dive into Knowledge for Free. Learn More!
We deal with a lot of text every day such as ‘Hi’, ‘Hello’, ‘Python’, names of people, and so on. In Python, these are called strings.
In this article, we will learn about stings, their features, and the different operations we can perform on them. So, let’s not wait and start learning to modify the names in Python!
Introduction to Python Strings
A string (str) in Python is a single character or a collection of characters. When we create a string, this internally converts into a combination of 1s and 0s for the computer to handle. This conversion of string to binary numbers is called encoding and is done using Unicode in Python.
In Python, a string can be created by enclosing it with either single or double quotes (‘’ or “”). For example,
Examples of creating a String in Python:
name1='Python' name2="PythonGeeks"
You cannot use a single quote at one end and a double quote at the other end. This will result in an error.
Example of getting an error on using single and a double quote:
name3='abcd"
Output:
And the type of these variables can be checked by using the built-in function type() as shown below.
Example of checking the data type of the variable holding text:
print("The type of ",name1,"is:",type(name1)) print("The type of ",name2,"is:",type(name2))
Output
The type of Python is: <class ‘str’>
The type of PythonGeeks is: <class ‘str’>
Creating Strings in Python
Besides creating simple strings, there might be a case where we have more than one line test, want to add quotes to the text. These cases are discussed below.
1. Creating multiline strings in Python:
To create a multiline string, one can use triple single or triple-double quotes at the ends of the string. The examples are shown below.
Examples of creating Python multiline strings:
multi_str='''Hi! Welcome to PythonGeeks.''' print(multi_str) multiStr="""Hello. How are you?""" print(multiStr)
Output:
Welcome to PythonGeeks.
How are you?
2. Creating strings with single and double quotes in Python:
To use double quotes, we have to enclose the strings with single quotes and vice versa. However, if we use single or double quotes inside and at the ends of the string, then we get an error. These different cases are covered in the below example.
Example of using quotes inside the strings:
str1='He said,"He loves Python!"' print(str1) str2="It's his favorite programming language" print(str2) str3='He then asked me, 'What's my favorite one?'' str4="I said "I do like Python""
Output:
He said,”He loves Python!”
It’s his favorite programming language
SyntaxError: invalid syntax
SyntaxError: invalid syntax
More on Python Strings
There are things we can perform on strings like access the substrings, modify them according to our purpose, etc. These we discuss in this section.
1. Accessing the character or a set of continuous characters in Python:
A string is like a list of characters. Any of the characters can be accessed using the index. An important thing to remember is that the indexing starts from 0.
a. Accessing a single character in Python:
To access a character we can use the string name followed by the index of that character in the square brackets. We can access from the right side also using negative indexing, where the rightmost character has ‘-1’ as the index.
An important note to remember is that a space is also a character in Python.
Example of accessing a character using the index in Python:
string="Python is fun!" print("string[2] is :",string[2]) # accessing the third character print("string[-1] is :",string[-1]) # accessing the last character
Output:
string[2] is : t
string[-1] is : !
b. Accessing multiple characters between two indexes :
To get a substring from ‘i’th index character to ‘jth’ index character(jth index character excluded), we can give indexing as ‘i:j’. This is called slicing. Here indexing starts from 0!. The values of i and j can be negative.
Example of accessing a set of characters using the index:
print("string[4:8] is :",string[4:8]) # accessing the characters from the 5th character to the 8th character print("string[-6:-2] is :",string[-6:-2]) # accessing the characters from the last 6th character to the last 4th character
Output:
string[4:8] is : on i
string[-6:-2] is : s fu
c. Accessing multiple characters before or after an index:
To get all the characters till the ‘ith’ index character (itself excluded), we give ‘ :i’. Similarly, to get all characters from ith character (itself included), we give ‘i:’.
Example of accessing a set of characters using the index:
print("string[3:] is :",string[3:]) # accessing all the characters from the 4th character print("string[-2: ] is :",string[-2:]) # accessing all characters from the last 2nd character print("string[:5 ] is :",string[:5]) # accessing characters till the 5th character print(string[:]) #printing the entire string print(string[3:3]) # printing empty string print(string[:-2]) #printing all the characters till the last 2nd character
Output:
string[-2: ] is : n!
string[:5 ] is : Pytho
Python is fun!
“
Python is fu
d. Getting an error on wrong indexing:
However, if the index exceeds the limit, then we get an error. Here the limit is one less than the length of the string ( number of characters in a string-1).
Example of getting an error on exceeding limit using the index:
print(string[22])
Output:
File “<pyshell#37>”, line 1, in <module>
print(string[22])
IndexError: string index out of range
e. Accessing characters with steps between them:
You can also get alternate characters from the string.
If we want to get alternate characters between the indexes i and j, slicing is ‘i:j:2’.
Here, alternate means every 2nd character is printed. Similarly, if we want every ‘kth’ character, we give ‘i:j:k’.
Example of slicing using index:
var="PythonGeeks" print(var[1:7:2]) #getting alternate characters between 2nd and 7th character print(var[::-3]) #getting every character at interval 3 from last
Output:
yhn
seoy
2. Immutability in Python
Strings are immutable, that is we cannot change or delete any character of the string. If we try doing so, we get an error.
Example of getting an error on trying to modify string:
str1='Python' str[3]='o' del str1[5]
Output:
File “<pyshell#1>”, line 1, in <module>
str[3]=’o’
TypeError: ‘type’ object does not support item assignmentTraceback (most recent call last):
File “<pyshell#5>”, line 1, in <module>
del str1[5]
TypeError: ‘str’ object doesn’t support item deletion
However, we can delete the entire string but we get a NameError if we try accessing the string after deleting.
Example of deleting the entire string:
string="Python" del string print(string)
Output:
File “<pyshell#2>”, line 1, in <module>
print(string)
NameError: name ‘string’ is not defined
3. Looping in Python
We can get each character of a string using loops. The most common loop used is the for loop. Here we use a variable as an iterator that goes through each character till it reaches the end of the string and does the operation inside the loop.
Example of printing each character of a string using looping:
string="Python Geeks" for char in string: #char is the iterator print(char)
Output:
y
t
h
o
n
e
e
k
s
4. Concatenation in Python
We can concatenate two or more strings using the ‘+’ operator’ and to add the same string, we can use the ‘*’ operator. We can also add space (“ “), in between the strings that are to be concatenated.
Examples of concatenation of strings:
greet='Hello' char='!' print(greet+char) print(greet*3) print(greet+" "+char*2)
Output:
Hello!
HelloHelloHello
Hello !!
To concatenate strings in two lines, we can use parentheses
Example of concatenating strings in different lines in Python:
string= ('Hello! Welcome to PythonGeeks.' 'Hope you are doing well') print(string)
Output:
Python String Formatters
There are many situations where we want to display other data types along with strings. A common method used is to separate them by commas as shown below.
Example of printing different data types along with strings using commas:
name ="abc" print(name, "'s age is", 32)
Output:
There are other ways to do so and they are:
1. Using f-strings in Python:
Here inside the print statement, we use f before the quotes enclosing the printing statement. And enclose the variable(s) holding the value in curly braces. These values can be of any data type.
Example of printing a f-string:
name="xyz" print(f"His name is {name}") father="abc" mother="pqr" print(f"His father's name is {father} and his mother is {mother}")
Output:
His name is xyz
His father’s name is abc and his mother is pqr
2. Using format() in Python:
We similarly use the format method as f sting. But instead, here the format function succeeds the text in double-quotes with the variable inside its curly braces. The variable can be of any data type.
Example of printing using format():
name='pqr' print("His name is {}".format(name)) dog="tom" age=4 print("He has a dog {} and it's age is {} years".format(dog,age))
Output:
His name is pqr
He has a dog tom and it’s age is 4 years
We can also use indexing or referring by using labels for each variable while printing using format(). And the braces with the index will be replaced with the value of the variable at that index in the list. For example,
Example of printing using indexing in format():
print("His name is {0} and his {2} years aged dog's name is {1}".format(name,dog,age)) print("His name is {n} and his {a} years aged dog's name is {d}".format(n=name,d=dog,a=age))
Output:
His name is pqr and his 4 years aged dog’s name is tom
His name is pqr and his 4 years aged dog’s name is tom
In this example, we can see that the first bracket has index 0, and the value of the variable at 0th index, name, is printed. Similarly, in the second bracket, age is printed, which is at the 2nd index. And in the 3rd bracket dog is printed which is at 1st index.
A string can be left or center justified using formatting using format specifiers using colons(:). We can use < for left justifying, ^ for center, and > for right. For example,
Example of justifying string using format():
String="Python" print("Left,centre and right alignment by formatting:") print("|{:<15}|{:^15}|{:>15}|".format(String,'is','fun'))
Output:
Left,centre and right alignment by formatting:
|Python | is | fun|
We can format numbers to binary, hexadecimal, etc. We can also change the float value to exponent form and also for rounding to specified decimal places.
Example of formatting numbers in Python:
print("Binary representation of 16 is: {0:b}".format(10)) print("Exponent form of of 13.56 is: {0:e}".format(13.56)) print("Rounding of 1/3 to 3 decimal places: {0:.3f}".format(1/3))
Output:
Binary representation of 16 is: 1010
Exponent form of of 13.56 is: 1.356000e+01
Rounding of 1/3 to 3 decimal places: 0.333
3. Using % operator in python
We can use the % operator followed by a character based on the data type to be printed and the value replaces that particular location. For string, we use %s, %d for integers, and %f for floats.
Example of printing strings using %s:
var="Python" print("The value in var is:%s"%(var)) lang="Programming language" print("%s is a %s"%(var,lang))
Output:
The value in var is:Python
Python is a Programming language
For floats, we can use % operator to control the number of decimal places to be printed after the decimal point. Examples are given below.
Example of printing floats using %f:
num=34.561235 print("The value with %3.2f formatting is:") print(" %3.2f " %num) print("The value with %3.5f formatting is:") print(" %3.5f " %num)
Output:
34.56
34.56124
Escape Sequences in Python
The escape sequences are used to add special characters, tabs, etc. These are preceded by backslash (‘\’) followed by a character depending on the requirement.
Common escape sequences are:
1. \t for tab
2. \n for a new line
3. \b for backspace
4. \\ for backslash
5. \’ for a single quote
6. \” for double quote
7. \r for carrier returning
8. \f for form feeding
9. \ooo for an octal value
10. \xHH for a hexal value
11. \a for ASCII bell
12. \v for vertical tab
Example of using Python escape sequences
name="PythonGeeks" print(f"You are visiting {name}\'s website.\n Hope you enjoy the read")
Output:
Hope you enjoy the read
Built-in functions for String in Python
There are many built-in functions in Python to handle strings. We will discuss the common ones with examples in this section.
1. len() in Python:
We can find the length of a string using the built-in operator len(). Again, do remember the spaces are counted while finding the length. The below example shows that.
Example of finding the length of a string:
string="Happy coding!" print(len(string))
Output:
2. str() in Python:
The str() function can be used for conversion from another data type to string. Some examples are shown below.
Example of converting to a string data type:
str1=str(4.5) print("The type of str1 is:",type(str1)) str2=str(7+0j) print("The type of str2 is:",type(str2)) str3=str({1,2,3.7,'a'}) print("The type of str3 is:",type(str3))
Output:
The type of str1 is: <class ‘str’>
The type of str2 is: <class ‘str’>
The type of str3 is: <class ‘str’>
3. Functions for Checking type of character in Python
The functions isdigit(), isalpha() and isspace() help in checking if a character(s) is a digit, alphabet, and space respectively. Examples of using these are shown below.
Example of using isdigit(), isalpha() and isspace():
var1='abc' print(var1.isalpha()) var2='aei4' print(var2.isalpha()) var3='234' print(var3.isdigit()) print(var2.isdigit()) var4=" " print(var4.isspace())
Output:
True
False
True
False
True
4. Converting the letter case in Python:
lower() and upper() convert the string into lower and upper case respectively. The way to use them is shown below.
Example of using Python lower() and upper():
print('abc'.upper()) str1="Python" print(str1.lower()) print(str1.upper())
Output:
ABC
python
PYTHON
5. Starting and ending letters:
The functions startswith() and endswith() can be used to find if the string starts or ends with a specifier character(s). It returns the output as either True or False.
Example of using Python startswith() and endswith():
name="PythonGeeks" name.endswith('ks') name.startswith('py')
Output:
False
6. Splitting and joining in Python:
The functions split() and join() can be used to either split a string or join to form a string by taking a character as a parameter. For further understanding, look at the below examples.
Example of using Python split() and join():
var="no-of-students" var.split('-') ",".join(['12','34','344'])
Output:
[‘no’, ‘of’, ‘students’]
‘12,34,344’
7. Find and replace in Python:
The functions find() and replace() can be used to search for the position of the substring and replace a substring with another one respectively. If the substring passed to find() is not there in the string, then it returns ‘-1’ as the output.
Example of using split() and join():
var="PythonGeeks" var.find('ee') var.find('py') var.replace('ee','EE')
Output:
7
-1
‘PythonGEEks’
8. Removing spaces in Python:
We can use strip() function to remove the trailing and leading spaces of a string. To remove only leading spaces, we can use lstrip(), and to remove trailing spaces we can use rstrip() functions. For example,
Example of using Python strip(), lstrip(), and rstrip():
string=" Python " print("On using strip():",string.strip(),".") print("On using lstrip():",string.lstrip(),".") On using lstrip(): Python . print("On using rstrip():",string.rstrip(),".") On using rstrip(): Python .
Output:
On using lstrip(): Python .
On using rstrip(): Python .
Other Python built-in functions include:
Function | Description |
capitalize(): | This function converts the first character of a string to uppercase |
casefold(): | This function converts the string into lowercase. It is similar to lower() but can work on strings of larger length |
center(width,fillchar): | This function takes a positive integer as length and a character as an argument. Returns a new string of specified length with the main string centered and the character filling the gaps on either side. |
count(start,begin,end): | This function returns the number of times a character (case sensitive) repeats in the string |
encode(): | This function returns the encoded version of the string |
decode(encoding = ‘UTF8’,errors = ‘strict’) | Decodes the string using rules of encoding. |
expandtabs(tabsize=8): | This function sets the tab size of the string if a tab character is used. |
find(): | This function returns the least location where the specified value occurs in the main string. It returns -1 if not found |
rfind(str,ben=,end=len(srt)) | This function returns the rightmost location, where the specified value occurs in the main string. |
rindex(): | This function returns the rightmost location, where the specified value occurs in the main string. |
format(), : | This function formats specified values of a string |
format_map() | This function formats specified values of a string |
isalnum(): | This function checks if all the characters of a string are either alphabets or numbers |
isdecimal(): | This function checks if all the characters are decimal values |
isidentifier(): | This function checks if the string is a Python identifier |
islower(): | This function checks if all the characters of a string are lowercase |
isupper(): | This function checks if all the characters of a string are uppercase |
isnumeric(): | This function checks if all the characters are of numeric type |
isspace(): | This function checks if all the characters are space |
isascii(): | Checks if all the characters are empty or ASCII values and returns True or False |
isprintable(): | This function returns True if all the characters are printable else False |
title(): | This function converts the string into title form (the first character of each word capitalized() |
istitle(): | This function checks if the string follows the rules of the title case |
ljust(width,[,fillchar]): | This function returns the left justified form of the string. If the specified length is more than the length of the string, then the spaces are filled with the specified character. |
rjust(width,[,fillchar]): | This function returns the right justified form of the string. If the specified length is more than the length of the string, then the spaces are filled with the specified character. |
maketrans(): | This function returns a translation table where each character of the given string is amped with the corresponding character of the second string based on the index. |
translate(table,deltechars=”): | This function returns the translated version of the string based on the mapping done using the translation table. |
partition(): | This function splits the string into 3 parts and returns a tuple with the parts as elements |
rpartition(): | This function splits the string into 3 parts by searching for the last occurrence of a specified string and returns a tuple |
rsplit(sep=None, maxsplit=-1): | This function splits the string based on a specified character and returns a list of the split parts |
splitlines(num=string.count(‘\n’)): | This function splits the string at new line breaks and returns a list of split values |
zfill(width): | Fills the string with 0s the specified number of times to the left and returns the resulting string |
swapcase(): | This function converts the lowercase character to uppercase and vice versa, for each character of a string |
String Constants in Python
There are some functions that give the constants in strings. These can be used on importing the string library.
Function | Description |
string.ascii letters | Returns all the capital and small alphabets as a string in ascii |
string.ascii lowercase | Returns all the lowercase alphabets as a string
in ascii |
string.ascii uppercase | Returns all the uppercase alphabets in ascii |
string.digits | Returns a string with all the digits |
string.hexdigits | Returns a string with all the hexadecimal digits |
string.letters | Returns all the capital and small alphabets as a string |
string.lowercase | Returns all the lowercase alphabets as a string |
string.uppercase | Returns all the uppercase alphabets as a string |
string.octdigits | Returns all the digits of octal system as a string |
string.punctuations | Returns all the ascii punctuations as a string |
string.printable | Returns all printable characters as a string |
Operators on Python Strings
Many operators can apply on strings to perform modifications, check relations, etc. Let us discuss them in this section.
1. Python Arithmetic Operators:
The arithmetic operators ‘+’ and ‘*’ can be applied to the strings. An example is shown below.
Example of applying arithmetic operators on Strings:
str1='abc' print(str1+str1) str2='1' print(str1*3+str2)
Output:
abcabc
abcabcabc1
2. Python Relational Operators:
Operators ==,!=,<,>,<=,>= can be used on strings that work by checking each character. For the operators <,>,<=, and >=, if any character shows the inequality, then it gives the results without checking the characters further.
Example of applying relational operators on Strings:
'12345'>'11678' 'abc'=='abc '
Output:
True
False
3. Python Logical Operators:
The logical operators like ‘and’, ‘or’ ‘not, etc can be applied on strings too. Here False is the presence of an empty string. For example,
Example of applying logical operators on Strings:
'' and 'abc' 'abc' and 'prw' '' or 'abc' not('')
Output:
‘prw’
4. Python Membership Operator:
The membership operators ‘in’ and ‘not in’ can be used to check if a substring exists in the string and give the output as either ‘True’ or ‘False’.
Example of using membership operators in Strings:
print('on' in name) print('geek' not in name)
Output:
True
5. Python Identity operators:
The operators ‘is’ and ‘is not’ are used to check if two strings are the same or not. These operators are case sensitive.
Example of using membership operators in Strings:
'Hi' is 'Hello' 'Python' is 'python' 'abc' is 'abc' 'abc' is not 'aBc' 'Python' is not 'PYTHON'
Output:
False
False
True
True
True
Interview Questions on Strings in Python
Q1. Given a name of a person with each word separated by spaces. How do you find the first name and last name?
Ans 1. We can use the split() function with the parameter as space (‘ ‘). For example,
Example of using Python split() function:
name="abc xyz" names=name.split(' ') print("First name is:",names[0]) print("Last name is:",names[1])
Output:
First name is: abc
Last name is: xyz
Q2. Given a code consisting of the first three characters as alphabets and the rest number of variable length. How to print the digits part?
Ans 2. We can use indexing to get the digits part. Since the first three characters are alphabets, we can use ‘3:’ indexing. For example,
Example of indexing to get substring:
code="ABC1234567890" print(code[3:])
Output:
Q3. Given a string check if the 2nd character is ‘a’/‘A’ or? Use the required built-in function?
Ans 3. We can use either the upper () or lower() function here to check. The below codes depict it.
Example of using upper() and lower():
var="ABC" var2=var.lower() print(var2[0]=='a') var3=var.upper() print(var3[0]=='A')
Output:
True
True
Q4. You would have heard of the joke, which says 1+1=11. Why not show that using coding in Python, if you have an integer 1 to you?
Ans 4. We can convert the integer into a string and concatenate it.
Example of concatenation:
num=1 string=str(num) print(string+string)
Output:
Q5. You are given a string “Hello, World!”. But you want to greet someone named “Bob”. How do you display the greeting using the above two strings only?
Ans 5. We can do slicing here to get the “Hello” and then concatenate it with the name as shown below.
Example of slicing and concatenation:
str1="Hello world!" str2="Bob" print(str1[:6] + str2 + str1[-1])
Output:
Quiz on Strings in Python
Conclusion
In this article, we learned about strings, their properties, printing methods, etc. We also saw operations and the application of built-in functions on strings. Finally, we practiced some interview questions.
Hoping that you understood the concepts. Happy coding!
Yes, I did enjoy the read. Thank you for this informative and helpful module!