在Python中迭代字符串并添加一些新字符
我需要在Python中迭代一个字符串,并在某些情况下在现有字符串之后添加一些空白字符。因此,我需要类似以下代码的smth(ofc,它不工作): 我还知道,我不能在迭代字符串对象时修改它 如何用Python编写这样的代码 例如: 输入--在Python中迭代字符串并添加一些新字符,python,python-2.7,Python,Python 2.7,我需要在Python中迭代一个字符串,并在某些情况下在现有字符串之后添加一些空白字符。因此,我需要类似以下代码的smth(ofc,它不工作): 我还知道,我不能在迭代字符串对象时修改它 如何用Python编写这样的代码 例如: 输入--“一些带空格字符的字符串” 可能的输出--“带空格字符的字符串”,“带空格字符的字符串”,“带空格字符的字符串”,等等 提前谢谢。我想: import re from random import randint text = 'this is some exam
“一些带空格字符的字符串”
可能的输出--“带空格字符的字符串”
,“带空格字符的字符串”
,“带空格字符的字符串”
,等等
提前谢谢。我想:
import re
from random import randint
text = 'this is some example text'
for i in xrange(5):
print re.sub(' ', lambda m: m.group() * randint(1, 3), text)
其中:
this is some example text
this is some example text
this is some example text
this is some example text
this is some example text
这是这样的,找到一个空格,然后用1到3个空格替换它。。。它应该足够直截了当,比循环/重新连接等更容易适应其他场景。我会选择:
import re
from random import randint
text = 'this is some example text'
for i in xrange(5):
print re.sub(' ', lambda m: m.group() * randint(1, 3), text)
其中:
this is some example text
this is some example text
this is some example text
this is some example text
this is some example text
这是这样的,找到一个空格,然后用1到3个空格替换它。。。它应该足够直截了当,比循环/重新连接等更容易适应其他场景。一个简洁的解决方案:
from random import choice
output = ''.join([choice([' ', ' ']) if c==' ' else c for c in input])
对于输入字符串中的每个字符,如果当前字符是空格,则输出随机选择的两个或三个空格;对于空间以外的任何输入,请复制到输出。然后,由于[list comprehension]
的结果是一个列表,因此将这些字符合并成一个新字符串。一个简洁的解决方案:
from random import choice
output = ''.join([choice([' ', ' ']) if c==' ' else c for c in input])
对于输入字符串中的每个字符,如果当前字符是空格,则输出随机选择的两个或三个空格;对于空间以外的任何输入,请复制到输出。然后,由于
[列表理解]
的结果是一个列表,请将字符连接起来,形成一个新的字符串。使用some\u string=list(some\u string)
-修改-''转换为列表。连接(some\u string)
?请放置一些输入和预期输出,以便易于求解。如果字符串是空格。。。然后将其保留为一个空格,随机设置为两个空格或三个空格?@Jon Clements我添加了一个空格example@FrozenHeart不清楚,伙计。请使用some\u string=list(some\u string)
-modify-''清楚地转换为列表。加入(some\u string)
?请放置一些输入和预期输出,以便易于求解。因此,如果字符串是空格。。。然后将其保留为一个空格,随机设置为两个空格或三个空格?@Jon Clements我添加了一个空格example@FrozenHeart不清楚,伙计。请讲清楚