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
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
I1234
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)
by reading your question, I understand you want to replace a certain character of your sting on a certain index, in your case replace character on index [0] with 'I',
my answer:
well as we know string's are immutable so we cannot just modify and replace a character directly, but their is a way to go around this, steps:
code:
string = "11234"
string_asList = list(string) #converts sting into list
string_asList[0] = "I" #replace element at [O] index
string = ''.join(string_asList) #converts list back to string
print(string)
'I' + string[1:]?II234, not11234, unless you're sayingtranslatedid nothing. I copied and pasted the code and gotII234as expected.I, and the OP specified a translation table.