String Manipulation in Python
String Manipulation in Python

String Manipulation in Python

String manipulation in python is the act of making changes to a string using python functions to get the desired result. In this article, you will learn about strings and how to manipulate them according to your needs. You can treat this article as an exhaustive cheat list for string manipulations in Python.

Strings are a datatype in python in which you can store alphanumeric characters along with punctuations. Normally, strings are used to manipulate text data in python.

Store a String in Python

To store a string inside a variable, you need to initialize it by putting the string inside double quotes. As python identifies the datatype through the way it is initialized, you do not need to specify the datatype anywhere.

# Initialize a string
str_var1 = "This is a string"

When the contents of a string are enclosed inside double quotes, you cannot make the double quotes a character in the string. However, you can include a single quote inside a string enclosed by double quotes.

#string with single quotes as its character
str1="Avid's Python"

You can also initialize a string by enclosing the characters in single quotes as shown below.

# Initialize a string with single quote
str_var1 = 'This is a string'

When using single quotes to enclose the characters of a string, you can include double quotes as a character in the python string.

#string with double quotes quotes as its character
str1='Avid"s Python'

When we try to put a single quote as a character inside a string enclosed by single quotes. The program will raise a syntax error. Similarly, if we put a double quote character inside a string enclosed by double quotes, the program will raise a syntax error.

Store a Multiline String in Python

You can store many lines inside a single string variable by using triple quotes. You can enclose the desired multiline string inside three double-quote characters and assign them to a variable as shown below.

# Storing multiple lines in string variable
str_var1 = """
    This is a string
    This is second line of the string
    This is third line of the string
    """

print(str_var1)

Output:

"C:/Users/Win 10/main.py"
This is a string
This is second line of the string
This is third line of the string

Process finished with exit code 0

We can also store multi-line strings using three single quotes. For this, you can enclose the multiline string inside three single quote characters as shown below.

# Initialize a string with single quotes
str_var1 = '''This is a string
This is second line of the string
This is third line of the string
'''

Another way to store a multiline string in python is by using parenthesis for initialization. In this case, we get a python tuple whose elements consist of each line of the multiline string.

# Initialize a string with parenthesis
str_var1 = ("This is a string",
            "This is second string",
            "This is third string")

print(str_var1)

When using parenthesis to store multiline strings, we need to use , as a delimiter.

"C:/Users/Win 10/main.py"
('This is a string', 'This is second string', 'This is third string')


Process finished with exit code 0

Print a String in Python

You can print a string in various ways. A simple way to print a string is by using the print() function. For this, you can pass the variable containing the string as an input argument to the print() function. After execution of the print() function, the string is printed in the console.

str_var1 = "This is string"
print(str_var1)

To Print the data type of a string variable, we use the type() function. The type() function takes a variable name as its input argument and returns the data type of the value contained in the variable. You can observe this in the following example.

str_var1 = "This is string"
num = 123
​
print(type(str_var1))
print(type(num))

Output:

"C:/Users/Win 10/main.py"
<class 'str'>
<class 'int'>

Process finished with exit code 0

You can see in the above example that the type() function is used to check the type of two variables – the first being a string carries str as its type, while the second variable storing numbers displays int as its type.

Concatenate Two Strings in Python

Concatenation and splitting are the two most common string manipulation techniques in Python.

You can manipulate strings in python by joining two strings or by splitting them. As Python treats everything as objects, you can concatenate two strings using the + operator as shown below.

str_var1 = "This is string "
str_var2 = 'and this is string 2'
​
print(str_var1 + str_var2)

Output:

"C:/Users/Win 10/main.py"
This is string and this is string 2
​
Process finished with exit code 0

In the above example, we have first created two variables containing different strings. Then, we concatenated the strings using the + operator.

Split a String in Python

Another technique to perform string manipulation in python is by splitting a string. You can split a string into a list of words by using the split() method.

When we invoke the split() method on a string, it takes a separator as its input argument. If we don’t pass any input argument to the split() method, the space character is used as the separator. After execution, the split() method splits the input string at each instance where the separator is present and returns a python list containing all the substrings of the input string. You can observe this in the following example.

# split a string
print("This is crazy".split())

Output:

"C:/Users/Win 10/main.py"
['This', 'is', 'crazy']
​
Process finished with exit code 0

In the above example, we haven’t passed any character as an input argument to the split() method. Hence, the input string on which the split() method is invoked is split at the space character. However, you can pass any character as a delimiter or separator to the split() method.

Use Delimiters to Split a String in Python at a Given Character

You can split a string based on a delimiter by providing it to the split() function as an input argument. For example, in the code snippet below, the string is split using comma characters as a delimiter in it.

# Split string as per the white spaces
str_var1 = "This,is,a,string"
​
print(str_var1.split(','))

Output:

The split() function splits the string into a list with four elements.

"C:/Users/Win 10/main.py"
['This', 'is', 'a', 'string']
​
Process finished with exit code 0

Split a String Using an Alphabet Character as Delimiter

Apart from special characters and white spaces, you can also use alphabet characters as a delimiter to split the string:

# Split string as per the white spaces
str_var1 = "This is string"
​
print(str_var1.split('i'))

Output:

"C:/Users/Win 10/main.py"
['Th', 's ', 's str', 'ng']

Process finished with exit code 0

In the above code, we have passed the letter I as input to the split() method. Hence, The function splits the string at every instance of i.

Split String by Passing an Argument as Delimiter

Splitting string this way is helpful when you need to extract data from a .csv file. For example, you can use , or . as a delimiter to extract precise information.

# Split with delimiters
str_var1 = "Jay,Shaw,22,India"
​
split_data = (str_var1.split(','))
for data in split_data:
    print(data)

Output: The above program uses a new variable split_data to store the split values, which get printed using the ‘for’ loop.

"C:/Users/Win 10/main.py"
Jay
Shaw
22
India
​
Process finished with exit code 0

Split String by Using the Partition() Function

Another way you can use string manipulation in python is by splitting the string using the partition() function. The partition() method is used to partition a string into different substrings. This function takes in a single parameter, which is the separator and returns a tuple of three values.

If the separator is found inside the string, it returns:

  • The part before the separator,
  • The separator,
  • The part after the separator.

Otherwise, it returns the complete string as the first value and two empty strings for the next two values.

In the code below, the partition() function is used to split the string:

s = "Delhi is the capital of India"
s2 = s.partition('capital')
print(s2)

Output:

"C:/Users/Win 10/main.py"
('Delhi is the ', 'capital', ' of India')
​
Process finished with exit code 0

Suggested Reading: When to Use Try-Except vs If-else in Python?

Join a List of Strings Using Join() Function in Python

In previous examples, you saw how the split() function splits a string into a list of words. The join() function in python works the exact opposite of the split() function. If you want to join some strings using a delimiter, you can invoke the join() method on the delimiter character and pass the list of strings that need to be joined as an input argument to the join() method. After execution, it returns a single string in which the input strings are used as substrings separated by the delimiter.

The example below uses a python list to store multiple words. In a new variable joined_data, the values from the list are joined using the join() function.

The join() function uses the delimiter – / to join the words but unlike its counterpart split(), it cannot work without a delimiter.

# Join values with join()
str_var1 = ["Jay", "Shaw", "22", "India"]
joined_data = ('/'.join(str_var1))
print(joined_data)
​

Output:

"C:/Users/Win 10/main.py"
Jay/Shaw/22/India

Process finished with exit code 0

Keep in mind that if you use the join() function without a delimiter, it causes an error:

str_var1 = ["Jay", "Shaw", "22", "India"]
joined_data = (join(str_var1))

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'join' is not defined

If you don’t want any additional characters in the joined string, you can use an empty string as a delimiter. After this, you will get the desired string without any extra characters. You can observe this in the following example.

myStr= ["Jay", "Shaw", "22", "India"]
joined_string = ("".join(myStr))
print(joined_string)

Output:

JayShaw22India

Use Arithmetic Operators on a String in Python

As we know that Python treats everything as objects, a string can be multiplied using the * operator, similar to what we did to concatenate two strings.

# Use '*' operator to multiply values inside a string
str_var1 = "Japan"
joined_data = str_var1 * 4
print(joined_data)

Output:

"C:/Users/Win 10/main.py"
JapanJapanJapanJapan

Process finished with exit code 0

In the above example, you can observe that we have multiplied the input string by 4 using the multiplication operator. Hence, we get a string having all the characters of the input string repeated 4 times. We have already seen how to use the + operator to concatenate two strings. However, we cannot use subtraction, division, or any other mathematical operator with strings. Doing so will lead to errors in the program.

Also, you can multiply a string with an integer and not with a floating point number or another string.

Change Capitalization of a String in Python

You can change the capitalization of a string by using various string manipulation functions in Python.

The upper() Method: You can change the capitalization of letters to uppercase by using the upper() function. When used on a string, it converts the string to uppercase and then returns the updated string as shown below.

str_var1 = "japan"
print(str_var1.upper())

Output:

"C:/Users/Win 10/main.py"
JAPAN
Process finished with exit code 0

The lower()Method: To change the case of the string to lowercase, you can use the lower() method in python. When we invoke the lower() method on a string, it is converted to lowercase.

str_var1 = "JAPAN"
​
print(str_var1.lower())

Output:

"C:/Users/Win 10/main.py"
japan
​
Process finished with exit code 0

The swap() Method: Instead of changing the capitalization of the whole string, you can alter specific parts of it. To swap the capitalization of all the letters at once, you can use the swap() method. The swap() method, when invoked on a string, swaps the case of the input string and returns a new string.

str_var1 = "Challenge Inside! : Find out where you stand!"
​
print(str_var1.swapcase())

Output:

"C:/Users/Win 10/main.py"
cHALLENGE iNSIDE! : fIND OUT WHERE YOU STAND!
​
Process finished with exit code 0

The captalize()Method: You can also try changing the capitalization of the first letter of a string by using the capitalize() method. The capitalize() method, when invoked on a string, capitalizes its first letter and returns the modified string. You can observe this in the following example.

str_var1 = "challenge Inside! : Find out where you stand!"
​
print(str_var1.capitalize())

Output:

"C:/Users/Win 10/main.py"
Challenge inside! : find out where you stand!
​
Process finished with exit code 0

Find or Replace a Part of String by String Manipulation in Python

An important part in string manipulation in python is find and replace operations. Let’s understand how to use the find() and replace() methods on strings.

The find() method is used to search the position of a character or a substring in a given string. When invoked on a string, the find() method takes a character or substring as its input argument. After execution, it returns the index of the substring’s first occurrence (if found). If the input character or substring isn’t present in the string, the find() method returns -1.

The find() method takes a maximum of three parameters, The first parameter is sub which is the substring to be searched in the string, and the other two are optional parameters start and end. The optional parameter provides the range (ex: str[start:end]) of the original string within which the substring is searched.

# Use find() to search for a substring
str_var1 = "This time around, the tree is a bigger and stronger one"

print(str_var1.find('around'))

Output:

"C:/Users/Win 10/main.py"
10

Process finished with exit code 0

You can find a substring inside a given string within a range by using the following syntax.

# Use find() to search for a substring inside a range
str_var1 = "This time around, the tree is a bigger and stronger one"

print(str_var1.find('around', 0, 36))

Python’s replace() method is used to swap out a portion of a string. You can use this method to replace every instance of the old character or text that matches the new character or text in the original string. The replace() method, when invoked on a string, takes the old character and the new character as its input arguments. After execution, it replaces the new character at every position of the old character in the original string and returns a new string as shown below.

# Use replace() to replace a substring
str_var1 = "possessed successive images that arose in my mind"

print(str_var1.replace('s', 'a'))

Output:

"C:/Users/Win 10/main.py"
poaaeaaed aucceaaive imagea that aroae in my mind
Process finished with exit code 0

String Manipulation in Python With Characters and White Spaces

You can add or remove white space and characters to a string with string manipulation in python.

Remove White Spaces From a String in Python

To remove white spaces from the start or end of a string, we use the strip() method. When invoked on a string, the strip() method removes the space characters at the start and end of the string and returns the modified string. In case you pass a string with no spaces characters at the start or end, it returns the string as it is.

# Use replace() to replace a substring
str_var1 = "            pen sing at concert                
print(str_var1.strip())

Output:

"C:/Users/Win 10/main.py"
pen sing at concert

Process finished with exit code 0

If you want to remove whitespace characters only from the start of a string, you can use the lstrip() method. To remove whitespace characters only from the end of a string, you can use the rstrip() method instead of the strip() method.

Add White Spaces to a String in Python

To add white space at the beginning of a string, you can use the rjust() python function, which right adjusts the given string with the character of your choice.

When invoked on a string, the rjust() method takes two input arguments. The first input is the number of characters that we need to justify the original string. The second input argument is the character with which we want to right justify the original string. To add whitespace to a string in python, you can pass the whitespace character to rjust() method as its second input argument.

my_str = 'pip'

adjust = my_str.rjust(6, ' ')
print(repr(adjust))

Output:

"C:/Users/Win 10/main.py"
'   pip'
Process finished with exit code 0

Another way through which you can add white spaces to your string is by using the * operator. This method can add white spaces not just at the beginning but also at the end.

my_str = 'image'

adjust = my_str + " " * 3
print(repr(adjust))  

Output:

"C:/Users/Win 10/main.py"
'image   '

Process finished with exit code 0

To add whitespace characters at the end of a string, you can also use the ljust() method. The ljust() method works in a similar manner to the rjust() method. It just adds the extra characters at the end of the original string instead of the start.

Another way you can add white space is by string manipulation in python using f-strings as shown in the following example.

my_str = 'image'
adjust = f'{my_str: >6}'
print(adjust)

Output:

"C:/Users/Win 10/PycharmProjects/python_socket/main.py"
       image

Process finished with exit code 0

String Manipulation in Python With Format Specifiers

A string can be manipulated to include a variable inside it. In Python, we can alter strings using a variety of string-manipulating techniques.

You can use Python’s format() function, f-strings, and % operator to manipulate strings in python.

Manipulate String in Python Using The % Operator

When the % operator is used on a string, it accepts a variable or tuple of variables as input and inserts them according to the % specifiers as shown below.

id = 5
name = "josh"
age = 23
str = "Employee id - %d is %s and he's %d" % (id, name, age)
print(str)

In the code above, we can see that three variables are initialized – id, name, and age. To print it using format specifiers, we use the appropriate % specifier to let the compiler know which variable we want to specify.

The first %d specifies the integer id, the next specifier %s specifies the string variable name, and the last denotes the integer age. At last, you provide a tuple to insert the variable names at the specified positions.

Manipulate Strings in Python Using the Format() Function

To use the format() function to manipulate string in Python, we use curly braces{} as placeholders for specifying the variable’s position. In the program below, there are three variables.

The curly braces are put inside the string at places where we need the variables. Then we use the format() function to specify the variables that we want to place inside the string as shown below.

id = 5
name = "josh"
age = 23
str = "Employee id - {} is {} and he's {}".format(id, name, age)
print(str)

Output:

"C:/Users/Win 10/main.py"
Employee id - 5 is josh and he's 23

Process finished with exit code 0

Manipulate Strings in Python by Using Positional Arguments

To get the variables to show up at a different position irrespective of the order in which the variables were declared, we use positional arguments inside curly braces.

Positional arguments are provided by looking at the sequence of variables declared inside the parameter. For example, inside parameter – (id, name, age), id has position 0, name has 1 and age has position 2.

Lastly, we put the position of arguments inside the curly braces as shown below.

id = 5
name = "josh"
age = 23

str = "{1} has id - {0} and he's {2}".format(id, name, age)

print(str)

Output:

"C:/Users/Win 10/main.py"
josh has id - 5 and he's 23
​
Process finished with exit code 0

Positional arguments are helpful when the programmer needs to rearrange the order of variables without changing a lot inside the code.

id = 5
name = "josh"
age = 23
​
str = "{1} has id - {2} and he's {0}".format(id, name, age)
​
print(str)

Output:

"C:/Users/Win 10/main.py"
josh has id - 23 and he's 5
​
Process finished with exit code 0

Manipulate String in Python Using Keyword Arguments

You can also specify variables using keyword arguments. These keywords are used as placeholders, and the input variables are passed as keyword arguments. The input parameters do not have to be given in the same sequence as the keywords in this procedure.

In the following code, the keywords are placed where we want the variable to show up, and then we assign the input variables to their respective keywords.

name = "Josh"
age = 23
id = 5
​
s = "{x} has id - {y} and aged = {z}".format(x=name, y=id, z=age)
​
print(s)

Output:

"C:/Users/Win 10/main.py"
Josh has id - 5 and aged = 23
​
Process finished with exit code 0

Use f-String to Manipulate String in Python

You can insert variables using formatted strings, also referred to as f-strings. We just need to insert variable names into placeholders created by curly braces {} to format strings using f-strings.

Upon program execution, the Python interpreter automatically updates the values of the variables defined in the placeholders as follows:

id = 5
name = "josh"
​
str = f"id of {name} is {id}"
​
print(str)

Output:

"C:/Users/Win 10/main.py"
id of josh is 5
​
Process finished with exit code 0

Using f-strings instead of format specifiers or the % operator has the benefit that data type of input variables don’t need to be taken into consideration. Since we enter variable names straight into the placeholders, no certain order is needed while specifying variables.

Conclusion

In this article, you learned in detail the techniques to manipulate strings in python. After going through the article, you will be able to easily manipulate strings in python, and use manipulation techniques to change formatting or insert variables.

To learn more about python programming, you can read this article on python SimpleHTTPServer. You might also like this article on python indexing.

Keep learning!

Donate to Avid Python

Dear reader,
If you found this article helpful and informative, I would greatly appreciate your support in keeping this blog running by making a donation. Your contributions help us continue creating valuable content for you and others who come across my blog. 
No matter how big or small, every donation is a way of saying "thank you" and shows that you value the time and effort we put into writing these articles. If you feel that our article has provided value to you, We would be grateful for any amount you choose to donate. 
Thank you for your support! 
Best regards, 
Aditya
Founder

If you want to Pay Using UPI, you can also scan the following QR code.

Payment QR Code
Payment QR Code

Leave a Reply