String Manipulation in Python

Estimated reading time: 2 minutes

Are you working with strings and need to quickly alter them so they look correct? We are going to take you through the following manipulations so you can quickly upskill on how to better manage them.

Python offers some very easy to use methods, which make the process of getting what you want the data to look like easier.

Find the length of a string

# Find the length of a string
text = "Fetchme"
print("Length is:", len(text))

result is: ===> Length is: 7

How to split a string variable – using one split value

text = "Hello,what is your name."
splittext = text.split(",") ==> One split value assigned.

result is: ===> ['Hello', 'what is your name.']

How to split a string variable – use more than one split value

text = "Hello,what is your name;My name is joe;test"
print(re.split(r'[,.;]', text)) ==> Notice that what you want to split on is between the [] brackets.

result is: ===> ['Hello', 'what is your name', 'My name is joe', 'test']

Find any character in a string

text = "Hello,what is your name."
print("First character is:", text[0])
print("Fifth character is:", text[5])
print("Sixth character is:", text[6])

First character is: H
Fifth character is: ,
Sixth character is: w

Print a string in an upper or lower case

text = "Joe"
print("Upper case:", str.upper(text)) #upper case
print("Lower case:",str.lower(text)) #lower case

Upper case: JOE
Lower case: joe

Concatenation of a string

first = "rainy"
last = "day"
name = first + last

the result is: rainyday

Testing a string value returns a Boolean value

testword = "abc123XSWb"
digits = "123"
print(testword.isalnum()) #check if all characters are alphanumeric
print(testword.isalpha()) #check if all characters in the string are alphabetic
print(digits.isdigit()) #test if string contains digits only
print(testword.istitle()) #test if string contains title words
print(testword.isupper()) #test if string contains upper case
print(testword.islower()) #test if string contains lower case
print(testword.isspace()) #test if string contains spaces
print(testword.endswith('b')) #test if string endswith a b
print(testword.startswith('H')) #test if string startswith H