pyt*_*der 5 python replace python-3.x
如何使用python单独替换字符串中的第一个字符?
string = "11234"
translation_table = str.maketrans({'1': 'I'})
output= (string.translate(translation_table))
print(output)
Run Code Online (Sandbox Code Playgroud)
预期输出:
I1234
Run Code Online (Sandbox Code Playgroud)
实际输出:
11234
Run Code Online (Sandbox Code Playgroud)
lmi*_*asf 15
我不确定你想要实现什么,但似乎你只想替换 a'1'一次'I',所以试试这个:
string = "11234"
string.replace('1', 'I', 1)
Run Code Online (Sandbox Code Playgroud)
str.replace采用 3 个参数old、new、 和count(可选)。表示要用子字符串count替换子字符串的次数。oldnew
在 Python 中,字符串是不可变的,这意味着您不能分配索引或修改特定索引处的字符。使用str.replace()代替。这是函数头
str.replace(old, new[, count])
Run Code Online (Sandbox Code Playgroud)
此内置函数返回字符串的副本,其中所有出现的子字符串old都替换为new。如果给出了可选参数count,则仅替换第一个出现的 count。
如果不想使用str.replace(),可以利用拼接的优势手动完成
def manual_replace(s, char, index):
return s[:index] + char + s[index +1:]
string = '11234'
print(manual_replace(string, 'I', 0))
Run Code Online (Sandbox Code Playgroud)
输出
I1234