Skip to main content
 首页 » 编程设计

python之在 Python 中迭代一个字符串并添加一些新字符

2025年05月04日27oomusou

在某些情况下,我需要在 Python 中遍历一个字符串并在现有字符之后添加一些空白字符。所以我需要类似下面的代码(当然,它不起作用):

for i, c in enumerate(some_string): 
  if c == ' ': 
    rand_value = random.randint(0, 2) 
    if rand_value == 0: 
      # Place two whitespaces here 
    elif rand_value == 1: 
      # Place three whitespaces here 

我还知道在遍历字符串对象时我不能修改它。

如何用 Python 编写这样的代码?

例子:

输入 -- “一些带有空白字符的字符串” 可能的输出——"some string with whitespace characters", "some string with whitespace characters", "some string with whitespace characters" 等

提前致谢。

请您参考如下方法:

我会去:

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 个空格替换它......它应该足够直接以适应其他场景,比循环/重新加入等更容易......