I have to create a code which will replace one character/letter from a string.
The example that I got was this:
string_substituting_char('abcdeeaa', 'c')
Should return:
'ab$deeaa'
And I know which code to use so I used this code, but I only know the code to replace all the letter in string:
def string_substituting_char (st, ch):
for ch in st:
st = st.replace(ch, '$')
return st
Code that I have and used (it replaces all the characters)
I want to know what should be added into the code so that it only changes one specific character from the string.
Simply return the result of the call to str.replace
:
def string_substituting_char(st, ch):
return st.replace(ch, '$')
Demo:
>>> def string_substituting_char(st, ch):
... return st.replace(ch, '$')
...
>>> string_substituting_char('abcdeeaa', 'c')
'ab$deeaa'
>>>
Or, if you want to only replace the first occurrence of a character, you can pass 1
to the count
parameter:
def string_substituting_char(st, ch):
return st.replace(ch, '$', 1)
Demo:
>>> def string_substituting_char(st, ch):
... return st.replace(ch, '$', 1)
...
>>> string_substituting_char('abcabc', 'c')
'ab$abc'
>>>
If you want to replace every instance of the given character use this:
>>> def string_substituting_char (st, ch):
... return st.replace(ch, '$')
...
>>> string_substituting_char('abccdefccsfdds', 'c')
'ab$$def$$sfdds'
Using regex
import re
def string_sub (str, ch):
return "$".join(re.findall("[^" + ch + "]+", str))
Demo:
>>> string_sub("ello this is aea sa s as", "e")
'$llo this is a$a sa s as'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.