We use strings in Python to handle text data. In this article, we will discuss basics of python strings and string manipulation in Python.
- What’s a String in Python?
- String Manipulation in Python
- String Slicing in Python
- Split a String in Python
- Check if a String Starts With or Ends With a Character in Python
- Repeat Strings Multiple Times in a String in Python
- Replace Substring in a String in Python
- Changing Upper and Lower Case Strings in Python
- Reverse a String in Python
- Strip a String in Python
- Concatenate Strings in Python
- Check Properties of a String in Python
- Conclusion
What’s a String in Python?
A python string is a list of characters in an order. A character is anything you can type on the keyboard in one keystroke, like a letter, a number, or a backslash. Strings can also have spaces, tabs, and newline characters. For instance, given below is a string in Python.
myStr="hello world"
Here, we have assigned the string “hello world” to the variable myStr. We can also define an empty string that has 0 characters as shown below.
myStr=""
In python, every string starts with and ends with quotation marks i.e. single quotes ‘ ‘, double quotes ” ” or triple quotes “”” “””.
String Manipulation in Python
String manipulation in python is the act of modifying a string or creating a new string by making changes to existing strings. To manipulate strings, we can use some of Pythons built-in methods.
Create a String in Python
To create a string with given characters, you can assign the characters to a variable after enclosing them in double quotes or single quotes as shown below.
word = "Hello World"
print(word)
Output:
Hello World
In the above example, we created a variable word
and assigned the string "Hello World"
to the variable. You can observe that the string is printed without the quotation marks when we print it using the print()
function.
Access Characters in a String in Python
To access characters of a string, we can use the python indexing operator [ ]
i.e. square brackets to access characters in a string as shown below.
word = "Hello World"
print("The word is:",word)
letter=word[0]
print("The letter is:",letter)
Output:
The word is: Hello World
The letter is: H
In the above example, we created a string “Hello World” and assigned it to the variable word
. Then, we used the string indexing operator to access the first character of the string and assigned it to the variable letter
.
Find Length of a String in Python
To find the length of a string in Python, we can use the len()
function. The len()
function takes a string as input argument and returns the length of the string as shown below.
word = "Hello World"
print("The string is:",word)
length=len(word)
print("The length of the string is:",length)
Output:
The string is: Hello World
The length of the string is: 11
In the above example, the len()
function returns 11 as the length of the string. This is due to the reason that there are 11 characters in the string including the space character.
Find a Character in a String in Python
To find the index of a character in a string, we can use the find()
method. The find()
method, when invoked on a string, takes the character as its input argument and returns the index of first occurrence of the character as shown below.
word = "Hello World"
print("The string is:",word)
character="W"
print("The character is:",character)
position=word.find(character)
print("The position of the character in the string is:",position)
Output:
The string is: Hello World
The character is: W
The position of the character in the string is: 6
In this example, we searched for the character "W"
in the string using the find()
method. As "W"
is present at index 6 of the string, the find()
method gives the value 6 as its output.
If the character is not present in the string, the find()
method gives -1 as its output. You can observe this in the following example.
word = "Hello World"
print("The string is:",word)
character="Z"
print("The character is:",character)
position=word.find(character)
print("The position of the character in the string is:",position)
Output:
The string is: Hello World
The character is: Z
The position of the character in the string is: -1
In this example, we passed the character "Z"
to the find()
method as its input. You can observe that the find()
method returns -1 as there is no "Z"
in the string "Hello World"
.
You can also find the index of a character or a substring in a string using the index()
method. The index()
method, when invoked on a string, takes a character or substring as its input argument. After execution, it returns the index of first occurrence of character or substring as shown below.
word = "Hello World"
print("The string is:",word)
character="W"
print("The character is:",character)
position=word.index(character)
print("The index of the character in the string is:",position)
Output:
The string is: Hello World
The character is: W
The index of the character in the string is: 6
Find Frequency of a Character in a String in Python
You can also perform string manipulation in python to find the frequency of a character in the string. For this, we can use the count()
method. The count()
method, when invoked on a string, takes a character as its input argument and returns the frequency of the character as shown below.
word = "Hello World"
print("The string is:",word)
character="l"
print("The character is:",character)
position=word.count(character)
print("The frequency of the character in the string is:",position)
Output:
The string is: Hello World
The character is: l
The frequency of the character in the string is: 3
In the above example, we used the count()
method find the frequency of the character "l"
in the string "Hello World"
. As there are three instances of "l"
in "Hello World"
, the count()
method gives 3 as its output.
Count the Number of Spaces in a String in Python
Spaces are also characters. Hence, you can use the count()
method count the number of spaces in a string in Python. For this, you can invoke the count()
method on the original string and pass the space character as input to the count()
method as shown in the following example.
myStr = "Count, the number of spaces"
print("The string is:",myStr)
character=" "
position=myStr.count(character)
print("The number of spaces in the string is:",position)
Output:
The string is: Count, the number of spaces
The number of spaces in the string is: 4
String Slicing in Python
To perform string manipulation in Python, you can use the syntax string_name[ start_index : end_index ]
to get a substring of a string. Here, the slicing operation gives us a substring containing characters from start_index
to end_index-1
of the string string_name
.
Keep in mind that python, as many other languages, starts to count from 0!!
word = "Hello World"
print word[0] #get one char of the word
print word[0:1] #get one char of the word (same as above)
print word[0:3] #get the first three char
print word[:3] #get the first three char
print word[-3:] #get the last three char
print word[3:] #get all but the three first char
print word[:-3] #get all but the three last character
word = "Hello World"
word[start:end] # items start through end-1
word[start:] # items start through the rest of the list
word[:end] # items from the beginning through end-1
word[:] # a copy of the whole list
To learn how all the statements in the above code work, read this article on string slicing in Python. You can also have a look at this article on string splicing.
Split a String in Python
You can split a string using the split()
method to perform string manipulation in Python. The split()
method, when invoked on a string, takes a character as its input argument. After execution, it splits the string at the specified character and returns a list of substrings as shown below.
word = "Hello World"
print(word.split(' ')) # Split on whitespace
Output:
['Hello', 'World']
In the above example, we have split the string at the space character. Hence, the split()
method returns a list containing two words i.e. 'Hello'
and 'World'
that are separated by the space character in the original string. You can pass any character to the split()
method to split the string.
If the character passed to the split()
method isn’t present in the original string, the split()
method returns a list containing the original string. You can observe this in the following example.
word = "Hello World"
print(word.split('Z')) # Split on whitespace
Output:
['Hello World']
In the above example, we passed the character "Z"
to the split()
method. As the character “Z"
is absent in the string 'Hello World'
, we get a list containing the original string.
Check if a String Starts With or Ends With a Character in Python
To check if a string starts with or ends with a specific character in Python, you can use the startswith()
or the endswith()
method respectively.
- The
startswith()
method, when invoked on a string, takes a character as input argument. If the string starts with the given character, it returns True. Otherwise, it returns False. - The
endswith()
method, when invoked on a string, takes a character as input argument. If the string ends with the given character, it returns True. Otherwise, it returns False. You can observe this in the following example.
In the above example, you can observe that the string "hello world"
starts with the character "h"
. Hence, when we pass the character "h"
to the startswith()
method, it returns True. When we pass the character "H"
to the startswith()
method, it returns False.
In a similar manner, the string "hello world"
ends with the character "d"
. Hence, when we pass the character "d"
to the endswith()
method, it returns True. When we pass the character "w"
to the endswith()
method, it returns False.
Repeat Strings Multiple Times in a String in Python
You can repeat a string multiple times using the multiplication operator. When we multiply any given string or character by a positive number N, it is repeated N times. You can observe this in the following example.
In the above example, you can observe that the string "PFB "
is repeated 5 times when we multiply it by 5.
Replace Substring in a String in Python
You can replace a substring with another substring using the replace()
method in Python. The replace()
method, when invoked on a string, takes the substring to replaced as its first input argument and the replacement string as its second input argument. After execution, it replaces the specified substring with the replacement string and returns a modified string.
You can perform string manipulation in Python using the replace()
method as shown below.
In the above example, you can observe that we have replaced the substring "Hello"
from the original string. The replace()
method returns a new string with the modified characters.
In the output, you can observe that the original string remains unaffected after executing the replace()
method. Hence, you can replace a substring in a string in Python and create a new string. However, the original string remains unchanged.
Changing Upper and Lower Case Strings in Python
You can convert string into uppercase, lowercase, and title case using the upper()
, lower()
, and title()
method.
- The
upper()
method, when invoked on a string, changes the string into uppercase and returns the modified string. - The
lower()
method, when invoked on a string, changes the string into lowercase and returns the modified string. - The
title()
method, when invoked on a string, changes the string into titlecase and returns the modified string. - You can also capitalize a string or swap the capitalization of the characters in the string using the
capitalize()
and theswapcase()
method.- The
capitalize()
method, when invoked on a string, capitalizes the first character of the string and returns the modified string. - The
swapcase()
method, when invoked on a string, changes the lowercase characters into uppercase and vice versa. After execution, it returns the modified string.
- The
You can observe these use cases in the following example.
Reverse a String in Python
To reverse a string in Python, you can use the reversed()
function and the join()
method.
- The
reversed()
function takes a string as its input argument and returns a list containing the characters of the input string in a reverse order. - The
join()
method, when invoked on a separator string, takes a list of characters as its input argument and joins the characters of the list using the separator. After execution, it returns the resultant string.
To reverse a string using the reversed()
function and the join()
method, we will first create a list of characters in reverse order using the reversed()
function. Then we will use an empty string as a separator and invoke the join()
method on the empty string with the list of characters as its input argument.
After execution of the join()
method, we will get a new reversed string as shown below.
string = "Hello World"
print(''.join(reversed(string)))
Output:
dlroW olleH
In the above example, you can observe that the original string is printed in the reverse order. Instead of the reversed()
function and the join()
method, you can also use the indexing operator to reverse a string as shown below.
string = "Hello World"
print(string[::-1])
Output:
'dlroW olleH'
Strip a String in Python
Python strings have the strip()
, lstrip()
, rstrip()
methods for removing any character from both ends of a string.
- The
strip()
method when invoked on a string, takes a character as its input argument and removes the character from start (left) and end(right) of the string. If the characters to be removed are not specified then white-space characters will be removed. - The
lstrip()
method when invoked on a string, takes a character as its input argument and removes the character from start (left) of the string. - The
rstrip()
method when invoked on a string, takes a character as its input argument and removes the character from the end(right) of the string.
We can strip the * characters from a given string using the methods as shown below.
In the above example, the original string contains "*"
character at its start and end. Hence, we need to pass the "*"
character to the strip()
, lstrip()
or rstrip()
method to strip it from the given string.
When we do not pass a character to the strip()
, lstrip()
or rstrip()
method, they take the space character as its value and strips the string on which they are invoked. You can observe this in the following example.
Concatenate Strings in Python
To concatenate strings in Python, you can use the “+” operator as shown below.
You can concatenate two or more strings using the + operator as shown above.
Check Properties of a String in Python
A string in Python can be tested for Truth value. For this, we can use different methods to check the properties of the string. The return type of these methods is of Boolean type (True or False).
Here is a list of some of the methods to check properties of a string in Python.
word = "Hello World"
word.isalnum() #check if all char are alphanumeric
word.isalpha() #check if all char in the string are alphabetic
word.isdigit() #test if string contains digits
word.istitle() #test if string contains title words
word.isupper() #test if string contains upper case
word.islower() #test if string contains lower case
word.isspace() #test if string contains spaces
word.endswith('d') #test if string endswith a d
word.startswith('H') #test if string startswith H
Conclusion
In this article, we have discussed different ways to perform string manipulation in Python. To learn more about python programming, you can read this article on list comprehension in Python. You might also like this article on how to build a chatbot in python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.