Python 有没有一种方法可以替换字符串中重复的单词,但只能替换特定的位置?
例如: 尝试替换\n但每3个\n不替换它,请将其想象为具有该重复的无限字符串 使用.Split“\n”拆分字符串 使用zip*[itersplit\U string+[]*组大小-lensplit\U string%组大小]*组大小对其进行分组 使用.join将每个组转换为组合字符串 使用“\n”重新组合字符串。加入 输出Python 有没有一种方法可以替换字符串中重复的单词,但只能替换特定的位置?,python,Python,例如: 尝试替换\n但每3个\n不替换它,请将其想象为具有该重复的无限字符串 使用.Split“\n”拆分字符串 使用zip*[itersplit\U string+[]*组大小-lensplit\U string%组大小]*组大小对其进行分组 使用.join将每个组转换为组合字符串 使用“\n”重新组合字符串。加入 输出 yes no yes yes no yes 使用.Split“\n”拆分字符串 使用zip*[itersplit\U string+[]*组大小-lensplit\U s
yes no yes
yes no yes
使用.Split“\n”拆分字符串
使用zip*[itersplit\U string+[]*组大小-lensplit\U string%组大小]*组大小对其进行分组
使用.join将每个组转换为组合字符串
使用“\n”重新组合字符串。加入
输出
yes no yes
yes no yes
为了好玩,这里有一个一行两行,因为您必须导入itertools:
>>> import itertools as it
>>> '\n'.join(map(''.join, it.zip_longest(*[iter(ExampleString.split('\n'))]*3, fillvalue='')))
'yes no yes\n yes no yes\n'
但我不建议这样做,因为它可能会使代码的任何读者感到困惑,因此我也不太愿意解释它。为了好玩,这里有一行两行,因为您必须导入itertools:
>>> import itertools as it
>>> '\n'.join(map(''.join, it.zip_longest(*[iter(ExampleString.split('\n'))]*3, fillvalue='')))
'yes no yes\n yes no yes\n'
但我不建议这样做,因为它可能会使代码的任何读者感到困惑,因此我也不太愿意解释它。替换特定位置上的单词或字符
str = 'yes\n no\n yes\n yes\n no\n yes\n'
new_character = ''
while(True):
position = int(input())
str = str[:position] + new_character + str[position + 1:]
print(str)
替换特定位置上的单词或字符
str = 'yes\n no\n yes\n yes\n no\n yes\n'
new_character = ''
while(True):
position = int(input())
str = str[:position] + new_character + str[position + 1:]
print(str)
这里有一个方法
s = "yes\n no\n yes\n yes\n no\n yes\n".split(" ")
# s => ['yes\n', 'no\n', 'yes\n', 'yes\n', 'no\n', 'yes\n']
s = " ".join([(c + 1) % 3 == 0 and s[c] or s[c][:s[c].find("\n")] for c in range(len(s))])
# s => "yes no yes\n yes no yes\n"
在这里,我们将其用于另一个字符串
s = "hi\n welcome\n okay\n thanks\n ok\n bye\n".split(" ")
# s => ['hi\n', 'welcome\n', 'okay\n', 'thanks\n', 'ok\n', 'bye\n']
s = " ".join([(c + 1) % 3 == 0 and s[c] or s[c][:s[c].find("\n")] for c in range(len(s))])
# s => "hi welcome okay\n thanks ok bye\n"
这里有一个方法
s = "yes\n no\n yes\n yes\n no\n yes\n".split(" ")
# s => ['yes\n', 'no\n', 'yes\n', 'yes\n', 'no\n', 'yes\n']
s = " ".join([(c + 1) % 3 == 0 and s[c] or s[c][:s[c].find("\n")] for c in range(len(s))])
# s => "yes no yes\n yes no yes\n"
在这里,我们将其用于另一个字符串
s = "hi\n welcome\n okay\n thanks\n ok\n bye\n".split(" ")
# s => ['hi\n', 'welcome\n', 'okay\n', 'thanks\n', 'ok\n', 'bye\n']
s = " ".join([(c + 1) % 3 == 0 and s[c] or s[c][:s[c].find("\n")] for c in range(len(s))])
# s => "hi welcome okay\n thanks ok bye\n"
您需要将列表拆分为其组成部分,然后将其分为3组。有了这个搜索词,你应该能够找到解决方案中缺少的部分。我该怎么做,很抱歉我不知道。什么部分让你困惑?如何搜索Python列表块?进行阅读,做出有效的尝试,然后再次尝试询问是否仍有问题。您需要将列表拆分为其组成部分,然后将其分为3组。有了这个搜索词,你应该能够找到解决方案中缺少的部分。我该怎么做,很抱歉我不知道。什么部分让你困惑?如何搜索Python列表块?进行阅读,做出有效的尝试,然后再次尝试询问是否仍然有问题。