Modify Python Strings

Modify Python Strings

4 mins read1.1K Views Comment
Updated on Apr 30, 2024 10:31 IST

Python string type provides various methods that can be used to modify the Python strings and implement common string-specific tasks. Let’s get started!

python string

 

Table of Contents

Changing the Capitalization of the Python Strings

Python offers a lot of built-in methods that act on the capitalization of a string. Two of the most common ones are:

  • str.upper
  • str.lower

Upper Case

str.upper method takes every character of the string and convert each of them their uppercase equivalent, for example:

x= "I Love Python!!" 
print(x.upper()) #upper() returns the string in Upper Case
 

Lower Case

str.lower method takes every character of the string and converts each of them their lowercase equivalent, for example:

x= "I Love Python!!" 
print(x.lower()) #lower() returns the string in Lower Case
 

Remove Whitespace in Python Strings

There are three string methods available to remove leading and trailing whitespace characters from the string. Each of these methods returns a new string leaving the original one unmodified.

Removing Leading and Trailing Whitespaces

The str.strip ([chars]) removes the leading and trailing characters contained in the argument chars. If you do not specify the chars argument, it will then by default remove the whitespace characters. This way we can use the str.strip method to remove both leading and trailing whitespaces from a string.

"    I Love Python!! "
print(x.strip()) #strip() method removes any whitespace from the beginning or the end
 

Removing Leading Whitespaces

We can use str.lstrip([chars]) to remove leading whitespace characters, that is, from the start of the string as shown below.

"    I Love Python!!   ".lstrip() #lstrip() method removes any whitespace from the beginning

Remove Trailing Whitespaces

We can use str.rstrip([chars]) to remove trailing whitespace characters, that is, from the end of the string as shown below.

"    I Love Python!!   ".rstrip() #rstrip() method removes any whitespace from the end

Replace a Python String

Python also offers a str method for replacing occurrences (all or any) of a substring with another substring in a given string. str.replace(old, new[ , count]) – The method takes two arguments old and new, the string to be replaced and the string with which it has to be replaced.

x= "I Love Python!!"
print(x.replace("I","U")) #replace() method replaces a string with another string
 

Split a String

We can split a string based on a delimiter into a list of strings using str.split() method. The syntax is as follows:

str.split(sep, maxsplit= -1) 

Here, the sep parameter is the delimiter string based on which one you want to split the string. If the sep argument value is not specified, the splitting takes place wherever there is whitespace. You should note that all the leading and trailing whitespaces are ignored and multiple consecutive sequences of whitespace characters are treated the same as single whitespace.

x= "I Love Python!!"
y= "I|Love|Python"
print(x.split(" ")) 
print(y.split("|"))
 

Python Strings Concatenation

There are several ways to concatenate a string, such as:

  1. Using + operator
  2. Using .join() method
  3. Using % Operator
  4. Using format() function
  5. Using, (comma)

Let us consider these two sentences and concatenate them using the above-mentioned methods,

x= “I Love Python “

y= “and Machine Learning”

Using + operator

+ operator can be used to concatenate Python strings and other Python sequence data types. Note that on concatenating, the original string does not get modified, instead we will be creating a new string.

x= "I Love Python "
y= "and Machine Learning"
z= x+y # + Operator is used to combine strings
print (z)
 

Using .join() method

You can use a string as a separator and use it to join a list of Python strings together into a single string using the join() method.

x= "I Love Python "
y= "and Machine Learning"
print("".join([x, y])) #join() method is used to combine the strings
z = " ".join([x, y]) #join() method is used here to combine the string with a separator Space(" ")
print (z)
 

Using % operator

You can combine strings using % operator. The best thing is along with concatenation you can also perform string formatting with % operator as shown below:

x= "I Love Python "
y= "and Machine Learning"
print("% s% s" % (x, y)) #% Operator is used here to combine the string
 

Using format() function

Just line % operator, the format() function is used for performing string formatting. If you look at the example below, you will notice that using format() is like any other function call.

x= "I Love Python "
y= "and Machine Learning"
print("{}{}".format(x, y)) #format function is used here to combine the string
 

Basically, the format function combines string stored in the variable x & y and stores it in another variable. You can see that positional arguments are used in the above example. Hence the {} cure;y braces, they set the position of the strings. Note that you can also pass keyword parameters to the format function.

Using comma (,)

I am pretty sure you don’t need an explanation for this. We have been using this throughout our blog in most of the examples. The comma (,) is the great alternative to using the + operator when you want to include single whitespace.

x= "I Love Python"
y= "and Machine Learning"
print (x,y) #, (comma) is used to combine the string
 

Apart from these, there are other string methods and alternative ways that you can use to modify strings.

Top Trending Tech Articles:
Career Opportunities after BTech | Online Python Compiler | What is Coding | Queue Data Structure | Top Programming Language | Trending DevOps Tools | Highest Paid IT Jobs | Most In Demand IT Skills | Networking Interview Questions | Features of Java | Basic Linux Commands | Amazon Interview Questions

Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio