Python strings are one of the most efficient tools for handling text data. In this article, we will discuss basics of python string and string manipulation in Python.
- What’s a String in Python?
- String Manipulation in Python
- Create a String
- Access characters in a String
- Find Length of a String
- Find a Character in a String
- Count the number of spaces in a string
- String Slicing
- Split Strings in Python
- Check if a string Startswith or Endswith a character
- Repeat Strings Multiple Times
- Replace Substring in a String in Python
- Changing Upper and Lower Case Strings
- Reverse a String in Python
- Strip a String in Python
- Concatenate Strings in Python
- Testing
- Conclusion
What’s a String in Python?
A python string is a list of characters in order. A character is anything you can type on the keyboard in one keystroke,
like a letter, a number, or a backslash.
Strings can have spaces:
"hello world".
An empty string is a string that has 0 characters.
Python strings are immutable
Python recognize as strings everything that is delimited by quotation marks
(” ” or ‘ ‘).
String Manipulation in Python
To manipulate strings, we can use some of Pythons built-in methods.
Create a String
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
Hello World
Access characters in a String
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"
letter=word[0]
>>> print letter
H
Find Length of a String
To find the length of a string, 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"
>>> len(word)
11
Find a Character in a String
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 word.find("H") # find the word H in the string
0
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 word.count('l') # count how many times l is in the string
3
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 and returns the index of first occurrence of character or substring as shown below.
>>> word = "Hello World"
>>> print word.index("World") # find the letters World in the string
6
Count the number of spaces in a string
To count the number of spaces in a string, you can pass the space character to the count() method as shown below.
s = "Count, the number of spaces"
>>> print s.count(' ')
8
String Slicing
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
Split Strings 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"
>>> word.split(' ') # Split on whitespace
['Hello', 'World']
In the above example, we have split the string at the space character.
Check if a string Startswith or Endswith a character
To check if a string starts with or ends with a specific character, 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.
word = "hello world"
>>> word.startswith("H")
True
>>> word.endswith("d")
True
>>> word.endswith("w")
False
Repeat Strings Multiple Times
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.
print "."* 10 # prints ten dots
>>> print "." * 10
..........
Replace Substring in a String in Python
You can also replace a substring with another substring using the replace() method. 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.
word = "Hello World"
>>> word.replace("Hello", "Goodbye")
'Goodbye World'
Changing Upper and Lower Case Strings
You can convert string into uppercase, lowercase, and titlecase 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 titlsecase 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 the swapcase() 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.
You can observe these use cases in the following example.
string = "Hello World"
>>> print string.upper()
HELLO WORLD
>>> print string.lower()
hello world
>>> print string.title()
Hello World
>>> print string.capitalize()
Hello world
>>> print string.swapcase()
hELLO wORLD
Reverse a String in Python
To reverse a string, 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))
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.
word = "Hello World"
You can Strip off newline characters from end of the string by passing “\n” as input argument to the rstrip() method.
>>> print word.strip('\n')
Hello World
strip() #removes from both ends
lstrip() #removes leading characters (Left-strip)
rstrip() #removes trailing characters (Right-strip)
>>> word = " xyz "
>>> print word
xyz
>>> print word.strip()
xyz
>>> print word.lstrip()
xyz
>>> print word.rstrip()
xyz
Concatenate Strings in Python
To concatenate strings in Python use the “+” operator as shown below.
"Hello " + "World" # = "Hello World"
"Hello " + "World" + "!"# = "Hello World!"
As discussed above, 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.
>>> print ":".join(word) # #add a : between every char
H:e:l:l:o: :W:o:r:l:d
>>> print " ".join(word) # add a whitespace between every char
H e l l o W o r l d
Testing
A string in Python can be tested for truth value.
The return type will be in Boolean value (True or False)
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.
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.