How to replace the first character alone in a string using python?
string = "11234" translation_table = str.maketrans({'1': 'I'}) output= (string.translate(translation_table)) print(output) Expected Output:
I1234 Actual Ouptut:
11234 23 Answers
I am not sure what you want to achive, but it seems you just want to replace a '1' for an 'I' just once, so try this:
string = "11234" string.replace('1', 'I', 1) str.replace takes 3 parameters old, new, and count (which is optional). count indicates the number of times you want to replace the old substring with the new substring.
In Python, strings are immutable meaning you cannot assign to indices or modify a character at a specific index. Use str.replace() instead. Here's the function header
str.replace(old, new[, count]) This built in function returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
If you don't want to use str.replace(), you can manually do it by taking advantage of splicing
def manual_replace(s, char, index): return s[:index] + char + s[index +1:] string = '11234' print(manual_replace(string, 'I', 0)) Output
1I1234
You can use re (regex), and use the sub function there, first parameter is the thing you want to replace, and second is the thing that you want to replace with, third is the string, fourth is the count, so i say 1 because you only want the first one:
>>> import re >>> string = "11234" >>> re.sub('1', 'I', string, 1) 'I1234' >>> It's virtually just:
re.sub('1', 'I', string, 1)