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
For just replacing the first character in the string, you need to pass maxreplace as 1. For example: >>> s = "Python is programming language" >>> s.replace ('n', 'o', 1) 'Pythoo is programming language' # ^ Here first "n" is replaced with "o" Return a copy of string s with all occurrences of substring old replaced by new.
Replace first n occurrence of a character in a string To replace the first n occurrences of characters of a string with another character, we can specify the optional input argument in the replace() method.
Python possesses many in-built functions to make programming easy and replace () method is one of them. replace () method helps to replace the occurrence of the given old character with the new character or substring.
The text [1:] returns the string in text from position 1 to the end, positions count from 0 so '1' is the second character. edit: You can use the same string slicing technique for any part of the string Or if the letter only appears once you can use the search and replace technique suggested below
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With