【发布时间】:2019-09-24 17:15:59
【问题描述】:
我正在尝试编写一种方法,将第一个字母之后的每个字母替换为“*”而不是字母。 例子: "babble" 产生 "ba**le" "that" 产生 "tha*"
我的代码在循环时似乎与替换函数有问题,我不太明白为什么。
def fix_start(s):
if len(s) < 2:
s = ""
else:
for i in s:
if i == s[0]:
if s[0]:
continue
s.replace(s[i], "*")
i += i
print(s)
【问题讨论】:
-
replace不会就地替换,它会返回一个新字符串。我没有检查你的其余代码,但你需要s = s.replace(...) -
这似乎没有奏效。
-
如前所述,我没有检查您的其余代码,因此其中可能存在其他问题。
标签: python string if-statement replace iteration