free stats

Python Modify Strings

Last Update : 18 Apr, 2023 Python, Programming

In this tutorial, you will learn to modify strings in Python.

Modifying strings in Python is used to changes to an existing string, such as concatenating strings, replacing substrings, slicing parts of the string, splitting the string into substrings, changing the case of the string, etc.

There are many string methods and operators available to modify strings in Python.

Example usage of modifying Python strings is as follows.

  • Join two strings using the + operator.
  • Replace a substring using the replace() method.
  • Extract a part of the string using slicing.
  • Split the string into substrings using the split() method.
  • Change the case of the string using the upper() and lower() methods.

 

How to concatenate two strings in Python?

String concatenate is merging two or more strings together.  There are different methods used to concatenate strings in Python. 

As an example, the concatenation of the string  "UX" and "Python" will result in "UXPython".

 

String concatenate using "+" operator

You can simply use the "+" operator between strings to concatenate strings. Here, more than two strings can be concatenated using the "+" operator.

Example -:

str1 = "Hello"
str2 = "UXPython"
str3 = str1 + str2
str4 = str1 + " " + str2
print(str3)
print(str4)

This program produces the following result -:

HelloUXPython
Hello UXPython

 

String concatenate using the join() method

You can use the join() method to join the sequence of elements. Also, more than two strings can be joined using the join() method.

Example -:

str1 = "Hello"
str2 = "UXPython"
str3 = "".join([str1,str2]);
str4 = " ".join([str1,str2]);
print(str3)
print(str4)

This program produces the following result -:

HelloUXPython
Hello UXPython

 

String concatenate using format() method

This is a string formatting function. Also, more than two strings can be concatenated using the format() method.

Example -:

str1 = "Hello"
str2 = "UXPython"
str3 = "{}{}".format(str1,str2);
str4 = "{} {}".format(str1,str2);
print(str3)
print(str4)

This program produces the following result -:

HelloUXPython
Hello UXPython

 

String concatenate using the % operator

You can use the % operator to concatenate two strings in Python.

Example -:

str1 = "Hello"
str2 = "UXPython"
str3="%s%s"%(str1,str2)
str4="%s %s"%(str1,str2)
print(str3)
print(str4)

This program produces the following result -:

HelloUXPython
Hello UXPython

 

You found this tutorial / article valuable? Need to show your appreciation? Here are some options:

01. Spread the word! Use following buttons to share this tutorial / article link on your favorite social media sites.

02. Follow us on Twitter, GitHub ,and Facebook.