Add a character to a specific position in a string in Python
In this tutorial, you will learn how to add a character to a specific position in a string in Python. When it comes to programming, strings are considered to be a sequence of characters, and in Python, strings are immutable, meaning they cannot be changed once created but we can add characters to the string to edit the string which further makes a new string.
Different methods or functions can be used to accomplish this process. Let us discuss all the possible methods in this tutorial.
By using the ‘+’ operator
Using’+’ we can concatenate strings and characters according to the desired position. Look at the code given below to clear your concept related to this method.
#Write the string s = "codespeed" s = s + 'y' # Adding a Character at end print(s) s1 = "coespeedy" s1 = s1[:2] + 'd' + s1[2:] # adding a Character at specific position print(s1) s2 = "odespeedy" s2 = 'c' + s2 # addig a Character at the starting print(s2)
Output:
codespeedy codespeedy codespeedy
By using join()
function
It is also possible in Python to concatenate characters at specific positions within a string by using join(). It is possible to add characters throughout the string, whether they be at the beginning, the end, or in the middle. In order to help you with your doubts, the following code is given.
#Write the string s = "codespeed" s = ''.join((s,'y')) #join the Character at end print(s) s1 = "coespeedy" s1 = ''.join((s1[:2],'d',s1[2:])) #join the Character at specific pos print(s1) s2 = "odespeedy" s2 = ''.join(("c",s2)) # join the Character at start print(s2)
Output:
codespeedy codespeedy codespeedy
By using format()
function
format() function is also a method to add characters to a specific position in a string in Python. It is also used for string formatting in Python. For reference look at the code given below:
s = "codespeed" s = "codespeed{}".format('y') #format() function to add Character at end print(s) s1 = "coespeedy" s1 = "co{}espeedy".format('d') # format() function to add Character at specific pos print(s1) s2 = "odespeedy" s2 = "{}odespeedy".format('c') # format() function to add Character at start print(s2)
Output:
codespeedy codespeedy codespeedy
Leave a Reply