如何替换多个索引 (Python) 处的字符串?
How do I replace a string at multiple indices (Python)?
我有一个字符串,我想替换该字符串的某些索引处的字符。但是我只知道如果我使用一个索引来替换一个字符:
word = word[:pos] + 'X' + word[pos + 1:]
pos 在这种情况下是索引。
但是当我现在有一个包含多个索引的列表时(所以 pos 现在是一个列表),它不起作用,因为切片索引必须是整数。
这里是一些更多的代码来提供更多的上下文:
string = 'HELLO WORLD'
secretword = ''.join('_' for c in string)
while True:
userinput = input("Give me a letter\n").upper()
if len(userinput) == 1:
if userinput in string:
pos = [i for i in range(len(string)) if string[i] == userinput]
secretword = secretword[:pos] + userinput + secretword[pos + 1:] #this does not work
print(secretword)
我必须说你的代码有点笨拙而且难以理解。
但是如果您想对索引列表应用相同的操作,那么只需遍历您的索引列表并应用相同的逻辑:
pos_list = [i for i in range(len(string)) if string[i] == userinput]
for pos in pos_list:
word = word[:pos] + 'X' + word[pos + 1:]
您可以简单地遍历数组:
while True:
userinput = input("Give me a letter\n").upper()
if len(userinput) == 1:
if userinput in string:
pos = [i for i in range(len(string)) if string[i] == userinput]
for p in pos:
secretword = secretword[:p] + userinput + secretword[p+1:]
print(secretword)
我有一个字符串,我想替换该字符串的某些索引处的字符。但是我只知道如果我使用一个索引来替换一个字符:
word = word[:pos] + 'X' + word[pos + 1:]
pos 在这种情况下是索引。 但是当我现在有一个包含多个索引的列表时(所以 pos 现在是一个列表),它不起作用,因为切片索引必须是整数。
这里是一些更多的代码来提供更多的上下文:
string = 'HELLO WORLD'
secretword = ''.join('_' for c in string)
while True:
userinput = input("Give me a letter\n").upper()
if len(userinput) == 1:
if userinput in string:
pos = [i for i in range(len(string)) if string[i] == userinput]
secretword = secretword[:pos] + userinput + secretword[pos + 1:] #this does not work
print(secretword)
我必须说你的代码有点笨拙而且难以理解。
但是如果您想对索引列表应用相同的操作,那么只需遍历您的索引列表并应用相同的逻辑:
pos_list = [i for i in range(len(string)) if string[i] == userinput]
for pos in pos_list:
word = word[:pos] + 'X' + word[pos + 1:]
您可以简单地遍历数组:
while True:
userinput = input("Give me a letter\n").upper()
if len(userinput) == 1:
if userinput in string:
pos = [i for i in range(len(string)) if string[i] == userinput]
for p in pos:
secretword = secretword[:p] + userinput + secretword[p+1:]
print(secretword)