我试图替换字符串中的第一个单词,尽管它不起作用。有帮助吗?
s = 'No word in this sentence is
capitalised.'
replacement = 'All'
s.split()
s.replace(s,replacement,0)
print(s)
答案 0 :(得分:1)
这里是获得所需结果的另一种方法:
s = 'No word in this sentence is capitalised.'
replacement = 'All'
s = s.split()
s[0] = replacement
print(' '.join(s))
s[1] = replacement
,s[2] = replacement
等答案 1 :(得分:0)
s.replace()
带有3个参数(您也可以通过自己运行help(s.replace)
来找出它们):
old
-您要替换的值内部 s
new
-用{li>替换old
的值
count
-替换次数因此,您需要这样做:
>>> s.replace("No",replacement,1)
'All word in this sentence is capitalised.'
答案 2 :(得分:0)
s = 'No word in this sentence is capitalised.'
replacement = 'All'
s = s.replace(s[:s.index(' ')], replacement, 1)
print(s)