Add Characters in String - Python
Last Updated :
10 Dec, 2024
A string is an immutable data type, which means we cannot manipulate it by adding, removing, or editing the original string. However, we can copy that string and then make the necessary changes. This means we can also add a character to a string by making a copy of it.
Let's start with a simple example of how to add a character to a string in Python.
Python
s = "GeeksForGeeks"
print(s, "!")
print("!", s)
OutputGeeksForGeeks !
! GeeksForGeeks
- Explanation: This example is simply printing the string "GeeksForGeeks" and inserted a character "!" at the start and end of that string.
Now, let us see different ways of adding a character to a String at various positions.
Using join() Function
The join() function is also used to concatenate two or more strings in Python. It takes an iterable, that is a list or a tuple as the parameters and join them in the given order.
Python
s = "GeeksForGeeks"
# Add character at the end
r1 = "".join([s, "!"])
# Add character at the start
r2 = "".join(["!", s])
print(r1)
print(r2)
OutputGeeksForGeeks!
!GeeksForGeeks
Using f-String
The f-string in Python is used in string formatting. It directly embeds the expression inside the curly braces. We can use f-strings to seamlessly add characters at the beginning, end, or any position within a string.
Python
s = "GeeksForGeeks"
# Add character at the end
r1 = f"{s}!"
# Add character at the start
r2 = f"!{s}"
print(r1)
print(r2)
OutputGeeksForGeeks!
!GeeksForGeeks
Using format() Function
The Python format() function is an inbuilt function used to format strings. Unline f-string, it explicitly takes the expression as arguments.
Python
s = "GeeksForGeeks"
# Add character at the end
r1 = "{}!".format(s)
# Add character at the start
r2 = "!{}".format(s)
print(r1)
print(r2)
OutputGeeksForGeeks!
!GeeksForGeeks
Using String Slicing
In string slicing, we just slice the list into two or more parts, breaking at the target position and then rejoining it after inserting the target substring in the middle.
Python
s = "GeeksForGeeks"
r1 = s[:-1] + "!"
r2 = "!" + s[0:]
# adding character at specific position
r3 = s[:5] + "!" + s[5:8] + "!" + s[8:]
print(r1)
print(r2)
print(r3)
OutputGeeksForGeek!
!GeeksForGeeks
Geeks!For!Geeks
Using List and insert() Function
In this method, we first convert the string to a list using list() method and then use list insert() function to insert a character at a specific position.
Python
s = "GeeksForGeeks"
a = list(s)
# Insert character at a specific position
a.insert(5, "!")
r1 = "".join(a)
print(r1)