Python String Manipulation: Methods and Examples
In Chapter 7, we’ll be looking at how to work with strings in Python. Strings are used everywhere in programming, and Python provides a lot of methods to make string manipulation easy. In this chapter, we’ll explore methods like count()
, find()
, replace()
, and more. We’ll also go through how to slice and concatenate strings, use membership operators, and split or join strings. By the end of this chapter, you should have a good understanding of how to handle strings and apply these concepts in your projects.
Basic String Operations
a = "python training and exercises"
print(len(a)) # 29
print(max(a)) # 'y'
print(min(a)) # ' '
Explanation:
len(a)
returns the length of the string, which is 29 characters including spaces.max(a)
returns the highest value character in the string based on the ASCII values. In this case,'y'
is the highest valued character.min(a)
returns the lowest value character, which in this case is the space character' '
because spaces have a lower ASCII value than letters.
String Slicing and Concatenation
a = "python"
b = "tutorial"
print(a[0:6] + ' tutorial') # 'python tutorial'
print(a + b) # 'python tutorial'
print(a * 3) # 'python python python'
print(a * 3 + b)# 'python python python tutorial'
Explanation:
a[0:6]
slices the stringa
from index 0 to 5 (excluding 6), giving us'python'
. Then, we concatenate it with the string' tutorial'
to get'python tutorial'
.- The
+
operator is used to concatenate (join) two strings. For example,'python' + 'tutorial'
results in'python tutorial'
. - The
*
operator repeats the string.a * 3
produces three copies of the string'python '
, resulting in'python python python'
. - You can also combine repetition and concatenation in the same expression, as shown with
a * 3 + b
.
Membership Operators with Strings
a = "python"
print('t' in a) # True
print('s' in a) # False
print('s' not in a) # True
print('t' not in a) # False
Explanation:
- The expression
't' in a
checks if the character't'
exists within the stringa
, returningTrue
. - Similarly,
's' in a
checks if's'
is in the string, returningFalse
since the letter's'
is not found in the word'python'
. not in
works in reverse:'s' not in a
evaluates toTrue
because's'
is not present in the string, and't' not in a
evaluates toFalse
because't'
is present.
Conditional Statements with Strings :
a = "interface eth0 is up"
if 'up' in a:
print("interface is up")
else:
print("interface is down")
Explanation:
This example shows how to use strings within an if
–else
conditional statement. The condition checks if the substring 'up'
is found in the string a
. If it’s present, the program prints "interface is up"
. If not, it prints "interface is down"
. This is particularly useful when checking for certain words in text-based inputs like system logs or commands.
String Methods: count()
, find()
, and index()
a = "python training and exercises"
print(a.count('n')) # 4
print(a.find('n')) # 5
print(a.index('n')) # 5
Explanation:
count('n')
returns the number of occurrences of the character'n'
in the string. In this case,'n'
appears 4 times.find('n')
searches for the first occurrence of'n'
in the string and returns its index, which is 5. If the character is not found, it returns-1
.index('n')
works similarly tofind()
, but instead of returning-1
when the character is not found, it raises aValueError
.
String Splitting, Joining, and Splitting Lines :
a = "192.168.1.1"
print(a.split('.')) # ['192', '168', '1', '1']
a = "python training"
print(a.split('n', maxsplit=2)) # ['pytho', ' trai', 'ing']
b = '.'
a = ['192', '168', '1', '2']
print(b.join(a)) # '192.168.1.2'
a = '''eth0 is up
eth2 is down
eth2 is up
eth3 is up'''
print(a.splitlines()) # ['eth0 is up', 'eth2 is down', 'eth2 is up', 'eth3 is up']
Explanation:
split('.')
splits the string based on the'.'
delimiter, returning a list of segments. This is commonly used for IP addresses.split('n', maxsplit=2)
splits the string based on'n'
, but only makes 2 splits, resulting in 3 segments.join()
joins a list into a string using a specified delimiter. In this example, the'.'
character is used to join the elements of the list['192', '168', '1', '2']
.splitlines()
splits a string into a list of lines based on line breaks. This is useful for handling multi-line strings.
Stripping Characters: strip()
, lstrip()
, rstrip()
:
a = "--------------------python training---------------------"
print(a.strip('-')) # 'python training'
print(a.lstrip('-')) # 'python training---------------------'
print(a.rstrip('-')) # '--------------------python training'
Explanation:
strip('-')
removes all leading and trailing'-'
characters from the string.lstrip('-')
removes only the leading'-'
characters, andrstrip('-')
removes only the trailing'-'
characters.
String Replacement with replace()
a = "python training"
print(a.replace('n', 'N')) # 'pythoN traiNiNg'
print(a.replace('n', 'N', 1)) # 'pythoN training'
a = "Interface Eth0 is up"
print(a.replace('up', 'down')) # 'Interface Eth0 is down'
Explanation:
replace('n', 'N')
replaces every occurrence of the letter'n'
with'N'
.- The third argument in
replace('n', 'N', 1)
limits the number of replacements to just one occurrence. - This method is helpful when you need to change specific characters or words in a string.
Case Conversions
a = "python training and exercises"
print(a.capitalize()) # 'Python training and exercises'
print(a.title()) # 'Python Training And Exercises'
print(a.upper()) # 'PYTHON TRAINING AND EXERCISES'
b = a.upper()
print(b.lower()) # 'python training and exercises'
Explanation:
capitalize()
capitalizes only the first letter of the string.title()
capitalizes the first letter of each word.upper()
converts the entire string to uppercase, andlower()
converts it back to lowercase.
Programming Exercises :
- Write a Python program to find the number of characters in a string (without using
len()
). - Write a Python program to count the number of occurrences of all vowels in a string.
- Write a Python program to find common characters present in two words.
- Write a Python program to check whether a given string is a palindrome.
- Write a Python program to convert alternate characters in a string to capital letters.
- Write a Python program to read an IP address from stdin and check whether it is valid.
- Write a Python program to read a date (dd-mm-yyyy) and print the month name according to the month number.
- Write a Python program to reverse a string without using built-in methods.
- Write a Python program to count the number of words in a sentence (without using the split() function).
- Write a Python program to remove all spaces from a string.
- Write a Python program to replace all occurrences of a given character in a string with another character.
- Write a Python program to read a sentence and print the longest word in that sentence.
- Write a Python program to check if two strings are anagrams (words formed by rearranging the letters of another, like “listen” and “silent”).
- Write a Python program to find all the words in a string that start with a vowel.
- Write a Python program to read a string and print the ASCII values of each character.
- Write a Python program to remove all digits from a given string.
- Write a Python program to process the following input data and perform two tasks:
- 17.1 Count and print the number of interfaces that are “up.”
- 17.2 Print the names of all interfaces that are “up”.
input_data = """Interface ethernet0 is up
Interface ethernet1 is down
Interface serial0 is down
Interface serial1 is up"""
We’d love to hear your feedback and suggestions about this article. Feel free to reach out to us using the WhatsApp number below.
About The Author:
Sajith Achipra has been a trainer and testing consultant at Zframez Technologies since 2009. With 15+ years of experience, he specializes in networking, Python, development, and testing. He conducts online courses to help students and professionals enhance their skills. You can reach him on WhatsApp at +91 8884 884 844 for your training and testing requirements.