【发布时间】:2020-08-05 19:42:44
【问题描述】:
由于 python 中的字符串是不可变的,我尝试了这个解决方法:我首先在其字符组件中破坏了字符串,将它们放在一个列表中。然后我继续在这个列表中循环并将我想修改的字符的第二次出现替换为目标字符。 最后一部分当然是从这样获得的新列表中重新构建字符串。
def modify():
space = " "
# This is the input part
varstr = input("Insert a string to modify:\n> ")
if space in varstr:
print("Please insert a string without space")
modify()
varchar = input("Insert a SINGLE character to modify in $:\n> ")
if len(varstr) > 1:
print("Please insert a single character, without spaces")
counter = 0
liststr = []
stringout = ""
#Creating the list composed by the characters of the string
for i in varstr:
liststr.append(i)
#Looping through the string and substituting the character from its second occurence
for j in range(len(liststr)):
if counter >= 1 and liststr[j] == varchar:
liststr[j] = "$"
elif counter == 0 and liststr[j] == varchar:
counter += 1
for k in liststr:
stringout += k
return stringout
我的问题是:这段代码可以更整洁一点吗?
编辑:示例输入可能是“Google”和字符“o”。那么样本输出将是
Go$gle
【问题讨论】:
-
使用样本输入和样本输出会更容易理解。请提供minimal reproducible example。
-
这将替换从第二个开始的所有事件。这是需要的吗?
-
我在文章末尾添加了示例输入和输出。
-
@schwobaseggl 是的!就是这样。