When working with strings in Python, there may be times when you want to add a character to a string, either at the beginning, end or somewhere in the middle. In this tutorial, you will learn how to add characters to strings in Python.
Step 1: Use the Concatenation Operator
Python allows you to concatenate strings using the concatenation operator +
. To add a character to a string, simply concatenate the character to the string.
1 2 3 |
original_string = "ello World" new_string = "H" + original_string print(new_string) |
Output:
Hello World
Step 2: Use slicing and string interpolation
You can use slicing and string interpolation to insert a character at a specific position in a string:
1 2 3 |
original_string = "Helo World" new_string = original_string[:3] + "l" + original_string[3:] print(new_string) |
Output:
Hello World
Step 3: Use the .join() method
The .join()
method is another way to insert a character into a string. You can create a sequence of characters by inserting a character at a specific position, and then use the .join()
method to join the characters back into a single string:
1 2 3 4 5 6 7 |
original_string = "Hell World" insert_char = "o" position = 4 new_string = "".join( (original_string[:position], insert_char, original_string[position:]) ) print(new_string) |
Output:
Hello World
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
original_string = "ello World" new_string = "H" + original_string print(new_string) original_string = "Helo World" new_string = original_string[:3] + "l" + original_string[3:] print(new_string) original_string = "Hell World" insert_char = "o" position = 4 new_string = "".join( (original_string[:position], insert_char, original_string[position:]) ) print(new_string) |
Conclusion
In this tutorial, you learned three different methods to add a character to a string in Python: using the concatenation operator, slicing and string interpolation, and the .join()
method. Choose the method that best fits your needs when working with strings in your Python projects.