python - 用字符串列表替换字符串元素,使用它们的索引

标签 python string python-3.x substring

我必须构建的函数是用(数字值 * 下一个字符)替换字符串中的数字。

因此,foo = '2 hs4q q2w2 ' 将变为 ' hsqqqq qww '(注意空格)

假设 - 数字不能为零。

我获取了数字的(索引,值)和下一个字符。使用该信息获取我需要放回字符串中的子字符串:

foo = '2 hs4q q2w2 '

parameters=[(int(foo_list[b]),b+1) for b in range(len(foo_list)) if foo_list[b].isdigit()]
parameters # list of tuples (digit,charindex to be extended)
#[(2, 1), (4, 5), (2, 9), (2, 11)]

for p,i in parameters:
    hoo=p*foo[i]
    print (hoo,type(hoo))

 #Out
   <class 'str'> # Two spaces
qqqq <class 'str'>
ww <class 'str'>
   <class 'str'> # Two spaces

如何在处理相似字符串的循环中使用所有这些信息?我知道字符串是不可变的,因此必须为每个插入/替换创建一个新的 str 对象。此外,索引值会随着循环运行而变化。

解决后的评论-

感谢大家提供四种不同的解决方案,这里供没有使用过yield from, yield的人引用 - In practice, what are the main uses for the new “yield from” syntax in Python 3.3?

最佳答案

个位数

您可以使用 str.isdigit 检查一个字符是否为数字,如果是则将其转换为 int 并将其与下一个字符相乘。这个逻辑可以写成给 str.join 的生成器。

代码

def expand_string(s):
    return ''.join([(int(c) - 1) * s[i+1] if c.isdigit() else c for i, c in enumerate(s)])

例子

foo = '2 hs4q q2w2 '
print(expand_string(foo)) # '  hsqqqq qww  '

尽管如此,对于多位数字的字符串,如 f10o',上面的代码失败了。

多位数

如果您还想考虑多位数字,您可以编写一个生成器函数,使用 itertools.groupby 将数字组合在一起。

代码

from itertools import groupby

def group_digits(s):
    for isdigit, group in groupby(s, str.isdigit):
        yield from [''.join(group)] if isdigit else group

def expand_string(s):
    s = list(group_digits(s))
    return ''.join((int(c) - 1) * s[i+1] if c.isdigit() else c for i, c in enumerate(s))

例子

foo = 'f10o'
print(expand_string(foo)) # 'foooooooooo'

关于python - 用字符串列表替换字符串元素,使用它们的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50548122/

相关文章:

python-3.x - 找到python字典中所有最大值的键?

python - 复数 numpy 的 sum 和 np.sum 之间的区别

Javascript重写数组

c - 将字符串中的数字更改为 int 的函数

python - 使用!=获得python while语句

Python 3.6.3 Idle 正在终止当前 session

python - 访问lru_cache的缓存

python - 我想使用 python27 读取 csv 文件,但出现类似“TypeError : 'encoding' is an invalid keyword argument for this function"”的错误

python - 正则表达式 sre_constants.error : bad character range

java - 为什么一个整数在放入数组后会改变值?