Add character to String in Python

Add character to String in Python

Strings are considered as a sequence of characters in programming. In Python, string objects are considered immutable. What this means is that string objects cannot be changed once created, and a new string is created with a different block of memory when we edit a string.

In this article, we will discuss how to add a character to string in Python.

Using the + operator

Apart from its arithmetic use, the + can also be used as a concatenation operator. It can combine one or more strings or characters based on our desired position. Given its flexibility and simple logic, this method is used very commonly for adding characters in a string.

In the following code, we will add a character at different positions in a string.

Output:

Python
Python
Python

In the above code, we added a character to a string at the start, end, and some particular index. While adding a character at some index, we simply slice the string into two substrings. One substring contains the part before the index and the other contains after the index. We simply concatenate the two substrings with the character in between to get the final result.

Using the join() function

The join() function can work on iterable objects for combining their constituents based on a specified separator character or string. It can be used to add a character in a string at our desired position.

For example,

Output:

Python
Python
Python

In the above example, we specify the separator character for the join() function as an empty character to avoid any space.

Using the % operator

In Python, we can use many methods to format strings and get the output in our desired form. We can use the % operator to format and add characters to a string.

For example,

Output:

Python
Python
Python

Using the format() function

The format() function is also used for string formatting in Python. It uses the same pattern to specify the format to add character to a string as discussed above.

For example,

Output:

Python
Python
Python

If any error is encountered in the above method, try changing the format to {0}.

Using the f-strings

The f-strings were introduced in Python 3 and are very popular when it comes to formatting strings in Python. It has an advantage over the % operator and format() function in terms of its speed and simplicity. We just have to prefix the string with f to use this method.

We can add a character to a string using this as shown below.

Output:

Python
Python
Python

That’s all how to add character to String in Python.

Was this post helpful?

Leave a Reply

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