Python - How To Add Character to String in Python

ID : 104

viewed : 252

Tags : PythonPython String

vote vote

98

This tutorial will explain the different methods to add a character to a string in Python. The string in Python is an immutable object, so all the methods which perform some action on a string return a new string. Suppose a user wants to add a character or number after randomly generating it to an existing string; this tutorial will look into different ways to add a character to a string.

Add a Character to a String in Python Using the + Operator

The + operator can concatenate two strings or a string and a character and returns a new string in Python. The example code below demonstrates how the + operator can be used to add a character to a string in Python.

print('The number is = ' + '2') 

Output:

The number is = 2 

Add a Character to a String in Python Using the join() Method

The string.join() method concatenates all the iterable object elements using the string as a separator between the elements. We can pass the string and the character as elements of a list to the string.join() method to add the desired character to the string.

The example code below demonstrates how to use the join() method to add a character to a string in Python:

print(" ".join(('The number is =', '2'))) 

Output:

The number is = 2 

  • Related HOW TO?