Learning Python? Here’s How to Manipulate Strings

Using Python you can manipulate strings in a number of ways. Python provides various functions, operators and methods that can be used to manipulate strings. You can slice a string, join two or more strings, interpolate variables in a string, and many more.

Strings in Python can be defined as a sequence of characters. They are immutable, meaning they cannot be modified once they are declared. Instead, a copy of the string is created for manipulation purposes.

How to Create Strings in Python

Creating strings in Python is as easy as assigning value to a variable in Python. You can use single quotes (‘ ‘), double quotes (” “), or three single(”’ ”’) /double quotes(“”” “””) to create strings.

str1 = 'Hello!'
str2 = "Hello!"
str3 = """Hello!"""
str4 = '''Hello!'''
print(str1)
print(str2)
print(str3)
print(str4)

Output:

Hello!
Hello!
Hello!
Hello!

The advantage of using a double quote for creating a string is that you can use a single quote character inside the double quote. Python will treat the single quote character as a part of the String.

s = "Using 'single quote' inside double quotes"
print(s)

Output:

Using 'single quote' inside double quotes

If you want to create a multiline string, then using three single quotes(”’ ”’) / three double quotes(“”” “””) is the best choice. While creating strings using single quotes (‘ ‘) or double quotes (” “), you need to use n escape character for a new line (line break). But by using three quotes, you don’t need to do that.

s1 = """This is a multiline
string using three double quotes"""
s2 = "This is a multiline
string using double quotes"
print(s1)
print(s2)

Output:

This is a multiline
string using three double quotes
This is a multiline
string using double quotes

How to Access String Characters

If you want to access individual characters, then Indexing is used; if you want to access a range of characters, then Slicing is used.

String Indexing

Just like any other Python data types, string indexes start with 0. The range of indexes is from 0 to length of the string – 1. Python strings also support negative indexing: -1 points to the last character of the string, -2 points to the 2nd last character of the string and so on.

s = "MAKEUSEOF"
# Prints whole string
print(s)
# Prints 1st character
print(s[0])
# Prints 2nd character
print(s[1])
# Prints last character
print(s[-1])
# Prints 2nd last character
print(s[-2])

Output:

MAKEUSEOF
M
A
F
O

You must use integers to access characters otherwise, you will get a TypeError. This will also happen if you will try to access elements that are out of range.

TypeError:

s = "MAKEUSEOF"
# TypeError will be thrown if you don't use integers
print(s[1.5])

Output:

TypeError: string indices must be integers

IndexError:

s = "MAKEUSEOF"
# IndexError will be thrown if you try to use index out of range
print(s[88])

Output:

TypeError: string indices must be integers

String Slicing

You can access a range of characters using the colon operator ( : ).

s = "MAKEUSEOF"
# Prints from 0th index(included) to 4th index(excluded)
print(s[0:4])
# Prints from 3rd last index(included) to last index(excluded)
print(s[-3:-1])
# Prints from 2nd index to last of the string
print(s[2:])
# Prints from start of the string to 6th index(excluded)
print(s[:6])

Output:

MAKE
EO
KEUSEOF
MAKEUS

How to Use Operators on Strings

Using the + Operator

The + operator is used to concatenate/join two or more strings. It returns the resultant concatenated string.

s1 = "MAKE"
s2 = "USE"
s3 = "OF"
s = s1 + s2 + s3
# Prints the concatenated string
print(s)

Output:

MAKEUSEOF

Using the * Operator

This is used to repeat a string a given number of times.

str = "MUO-"
# Prints str 5 times
print(str * 5)
# Prints str 2 times
print(2 * str)
x = 3
# Prints str x times
# Here, x = 3
print(str * x)

Output:

MUO-MUO-MUO-MUO-MUO-
MUO-MUO-
MUO-MUO-MUO-

Using the in Operator

This is a membership operator which checks if the first operand is present in the second operand or not. If the first operand is present in the second operand then it returns True.

Otherwise it returns False.

str = "MAKEUSEOF"
# Returns True as MAKE is present in str
print("MAKE" in str)
# Returns False as H is not present in str
print("H" in str)

Output:

True
False

Using the not in Operator

Another membership operator, not in works opposite to the in operator. If the first operand is present in the second operand, it returns False. Otherwise it returns True.

str = "MAKEUSEOF"
# Returns True as Hello is not present in str
print("Hello" not in str)
# Returns False as M is present in str
print("M" not in str)

Output:

True
False

Escape Sequences in Strings

Using the escape sequences you can place special characters in the string. All you need to do is add a backslash (/) just before the character you want to escape. If you don’t escape the character, Python throws an error.

s = 'We are using apostrophe ' in our string'
print(s)

Output:

We are using apostrophe ' in our string

How to Insert Variables in Strings

Variables can be used inside the strings by interpolating variables in curly braces. Also, you need to add a lowercase f or uppercase F just before opening the quote of the string.

s1 = "Piper"
s2 = "a"
s3 = "pickled"
str = f"Peter {s1} picked {s2} peck of {s3} peppers"
# s1, s2 and s3 are replaced by their values
print(str)
a = 1
b = 2
c = a + b
# a, b and c are replaced by their values
print(f"Sum of {a} + {b} is equal to {c}")

Output:

Peter Piper picked a peck of pickled peppers
Sum of 1 + 2 is equal to 3

How to Use Built-in String Functions

len() Function

This function is used to find the length of the string. It is one of the most used functions in Python.

str = "MAKEUSEOF"
# Prints the number of characters in "MAKEUSEOF"
print(len(str))

Output:

9

ord() Function

Meanwhile this function is used to find the integer value of a character. Python is a versatile language, it supports ASCII as well as Unicode characters.

c1 = ord('M')
c2 = ord('a')
c3 = ord('A')
c4 = ord('$')
c5 = ord('#')
print(c1)
print(c2)
print(c3)
print(c4)
print(c5)

Output:

77
97
65
36
35

chr() Function

Use chr() to find the character value of an integer.

i1 = chr(77)
i2 = chr(97)
i3 = chr(65)
i4 = chr(36)
i5 = chr(35)
print(i1)
print(i2)
print(i3)
print(i4)
print(i5)

Output:

M
a
A
$
#

Related: What Is ASCII Text and How Is It Used?

str() Function

Use this function to convert any Python object to a string.

num = 73646
# Converts num (which is integer) to string
s = str(num)
# Prints the string
print(s)
# Type functions returns the type of object
# Here, is returned
print(type(s))

Output:

73646

How to Join and Split Strings in Python

Splitting a String

You can use the split() method to split the string into a list of strings based on a delimiter.

str1 = "Peter-Piper-picked-a-peck-of-pickled-peppers"
splitted_list1 = str1.split('-')
# Prints the list of strings that are split by - delimiter
print(splitted_list1)
str2 = "We surely shall see the sun shine soon"
splitted_list2 = str2.split(' ')
# Prints the list of strings that are split by a single space
print(splitted_list2)

Output:

['Peter', 'Piper', 'picked', 'a', 'peck', 'of', 'pickled', 'peppers']
['We', 'surely', 'shall', 'see', 'the', 'sun', 'shine', 'soon']

Joining Strings

You can use the join() method to join all the elements of an iterable object. You can use any delimiter you want to join the elements.

list1 = ["I", "thought", "I", "thought", "of", "thinking", "of", "thanking", "you"]
# Joins the list as a string by using - as a delimiter
str1 = "-".join(list1)
print(str1)
list2 = ["Ed", "had", "edited", "it"]
# Joins the list as a string by using a single space as a delimiter
str2 = " ".join(list2)
print(str2)

Output:

I-thought-I-thought-of-thinking-of-thanking-you
Ed had edited it

Now You Understand String Manipulation

Dealing with strings and texts is an integral part of programming. Strings act as a medium to communicate information from the program to the user of the program. Using Python you can manipulate the strings the way you want.

Source: makeuseof.com

Related posts

Connections #327: Today’s Answer and Clues (Friday, May 3, 2024)

7 Features Smartphone Cameras Need to Beat DSLRs

Are Early Access Games Worth It? The Pros and Cons Explained