How can I insert a character into a specific position in a string in Python?

How can I insert a character into a specific position in a string in Python?

Hi,

In Python, strings are immutable, so you cannot directly modify a string at a specific position.

However, you can create a new string with the character inserted. For example, given the string “3655879ACB6”, to insert a “-” at position 4, you can use string slicing:

s = '3655879ACB6'
s = s[:4] + '-' + s[4:]
print(s)  # Output: '3655-879ACB6'

Convert the string into a list, insert the character, and then join the list back into a string.

s = '3655879ACB6'
lst = list(s)
lst.insert(4, '-')
s = ''.join(lst)
print(s)

Output: ‘3655-879ACB6’