Home » Beginner’s Guide to String Manipulation in Python

Beginner’s Guide to String Manipulation in Python

Beginner’s Guide to String Manipulation in Python
Image by Editor | ChatGPT

 

Introduction

 
Strings are one of the most commonly used data types in Python. There is a high chance that you will use strings while working with Python in one way or another during your development journey or career, be it as a data scientist, software engineer, DevOps engineer, or other similar professional who often works with Python. Learning to work with strings seamlessly is an invaluable skill that must be in every aspiring Python developer’s toolkit.

In this article, you will learn about strings in Python and various techniques for manipulating them. This article is suitable for beginners with a working knowledge of Python programming who intend to learn about strings and how to work with them by exploring different manipulation methods.

 

What are Strings in Python?

 
A string in Python is a primitive data type and an object of the str class. As an object, it has access to the many methods provided by the str class that can be used for string manipulation. The building block of strings is characters; a string can contain one or more characters, including whitespace, enclosed in double or single quotes. This could be a number or sequence of numbers, a letter or a sequence of letters, or a combination of these and other symbols.

Listed below are some of the key characteristics of strings:

 

// Immutability

Strings in Python are immutable, meaning that once they are created, they cannot be changed. When you create a string in Python, the object occupies a space in memory. That particular object cannot be changed; rather, any modification or manipulation made to the string object leads to the creation of a new string.

See the example code below:

name = "big"
print(name.upper())
print(name)

 

Output:

 

The code snippet above shows that the variable name remained unchanged even after calling the upper() method on it.

 

// Ordered Nature

Strings represent an ordered sequence of characters, which enables every character in a string to have a specific position or index.

 

// Indexable

Characters in a string can be accessed through their index. Python indexes start at zero (0), which means that the first character of a string can be accessed with index 0.

 

// Iterability

You can loop through every character in a string using a for loop to perform a desired operation.

 

Creating and Using Strings in Python

 
To create a string in Python, follow the steps below:

Step 1: Open your IDE and create a file for this practice exercise, e.g. practice.py.

Step 2: Create a variable and store the string in it as shown below:

my_string = "Hello world, I just created a string in Python"
print(my_string)

 

Run the program. That’s it. You’ve undoubtedly done this before.

In the example above, we simply created a string, stored it in a variable, and printed it. However, there are many other operations we can carry out with strings. For example, we can write a program that receives an input string from a user, processes it, and prints an output. See the code snippet below for implementation.

Create a new file named practice2.py and write the following code in it:

name = input("What is your name: ")
print(f"Welcome {name}, thank you for using our program.")

 

When you run the program, you should see an interactive shell.

In the code above, we created a program that asks a user for their name and returns a greeting message. The user’s name was stored in a variable (name) and later processed in the program to be part of the output message. An f-string was used by placing the letter f before the double quotes. Inside the quotes, the name variable is placed between curly brackets. F-strings ensure that expressions inside curly brackets are evaluated, which is why the value stored in the name variable was printed to the console after running the program.

 

Manipulating Strings in Python

 
String manipulation is the process of altering or modifying strings programmatically to serve a certain purpose. When utilized properly, string manipulation has numerous benefits. For example, a data scientist could use it to clean a dataset, or a software engineer could use it to process text input.

Python comes with many built-in methods that can be used to manipulate strings, as you will find listed below.

 

// Switching Between Uppercase and Lowercase

To change a string to uppercase, you simply call the upper() method on the string as shown below:

name = "John"
uppercase_name = name.upper()
print(uppercase_name)

 

Output:

 

You can also convert a string from uppercase to lowercase by calling the lower() method on the uppercase_name variable.

print(uppercase_name.lower())

 

Output:

 

// Replacing Substrings

If you ever need to replace a substring with something else, the replace() method is your go-to. It replaces all occurrences of the existing substring with another, returning a new string. Because strings are immutable, you must assign the result to a new variable.

text = "Hello strangers"
new_text = text.replace("strangers", "family")
print(new_text)

 

Output:

 

// Splitting a String

A string can be split into a list of substrings using split() and a specified delimiter.

text = "Hello, World"
print(text.split(","))

 

Outut:

 

// Joining Strings

While the split() method separates a string into a list, the join() method joins the elements of a list into a single string, using a chosen separator.

words = ["Hello", "World"]
print(" ".join(words))

 

Output:

 

// Counting Substring Occurrences

The count() method is used to find the number of times a substring appears in a string.

text = "Hello World"
print(text.count("l"))

 

 

// Counting String Length

The length of a string can be calculated by invoking the built-in len() function.

text = "Hello World"
print(len(text))

 

 

// Removing Whitespace or Specified Characters From String

Whitespace at the beginning (leading) and end (trailing) of a string can be removed. The lstrip() method removes leading whitespace, and rstrip() removes trailing whitespace. The strip() method removes both. It can also be used to remove specified leading and trailing characters.

# Example string with extra spaces and symbols
text = "   **Hello World!!**   "

# Using strip() to remove spaces from both sides
stripped_text = text.strip()
print(stripped_text)"

# Using lstrip() to remove spaces from the left side
left_stripped_text = text.lstrip()
print(left_stripped_text)

# Using rstrip() to remove spaces from the right side
right_stripped_text = text.rstrip()
print(right_stripped_text)

# Using strip() to remove specific characters (*, !, and spaces) from both sides
custom_stripped_text = text.strip(" *!")
print(custom_stripped_text)

# Using lstrip() to remove specific characters (*, !, and spaces) from the left side
custom_left_stripped_text = text.lstrip(" *!")
print(custom_left_stripped_text)

# Using rstrip() to remove specific characters (*, !, and spaces) from the right side
custom_right_stripped_text = text.rstrip(" *!")
print(custom_right_stripped_text)

 

Output (in order of operation):

"**Hello World!!**"
"**Hello World!!**   "
"   **Hello World!!**"
"Hello World"
"Hello World!!**   "
"   **Hello World"

 

// Checking Case

To check if all characters in a string are a specific case, you can use the isupper() or islower() methods. These methods return a boolean value (True or False).

print("HELLO".isupper())
print("hello".islower())
print("HeLLo".islower())

 

 

Conclusion

 
This article introduced you to strings and explained how they can be interacted with programmatically in Python. You have learned what strings are, as well as how to create, use, and manipulate them using some built-in methods available in Python. Although this article did not cover all the methods available for string manipulation, it has established the fundamental principles for manipulating strings.

Practice the examples given in this article on your own to consolidate your learning.

Thanks for reading.
 
 

Shittu Olumide is a software engineer and technical writer passionate about leveraging cutting-edge technologies to craft compelling narratives, with a keen eye for detail and a knack for simplifying complex concepts. You can also find Shittu on Twitter.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *