由于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
解决方案:
你可以这样做。
char = "a"
stri = "santaclaus"
char.join("$".join(s.split(char)) for s in stri.split(char, 1))
# 'sant$cl$us'
这在第一条就被拆开了 char
的发生,并在””之后将代币连接起来。char.split
婷婷和 '$'.join
ing “他们。