Python: How to insert characters in specific positions of a string.
A simple guide on how to insert characters in specific positions of a string in Python.
How to Insert Characters in Specific Positions of a String in Python
When doing data processing with Python a very common task is to insert characters at the beginning or at the end of a string, it's quite an easy task.# Insert to the start of a string
new_string1 = "text_to_insert"+old_string
# Insert to the end of a string
new_string2 = old_string+"text_to_insert"
But how we can insert characters in a specific position of a string? This task can be done using list slicing. We slice the string into two parts, breaking at the target position and then rejoining it after inserting the characters at the target position.
Create the following function:def inserter(s,a,n):
"""
s: The original string
a: The characters you want to append
n: The position you want to append the characters
"""
return s[:n]+a+s[n:]
Explanation:
The return line does all the job, slices the given string into two lists: one from the start of the string to position ‘n’ and a second one starting from position ‘n’ to the end of the string, and we glue together the two slices with the characters that we want to insert, then we return the new string.
Create the following script and execute it:#!/usr/bin/env pythondef inserter(s,a,n):
"""
s: The original string
a: The characters you want to append
n: The position you want to append the characters
"""
return s[:n]+a+s[n:]if __name__ == '__main__':original_string = "My car is a mazda."
characters2insert = " old"
position = 2print(original_string)
new_string = inserter(s = original_string, \
a = characters2insert, \
n = position)
print(new_string)
The output of the script should be:My car is a mazda.
My old car is a mazda.
I hope you found the article useful easy to understand and enjoyable :)
More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.