【发布时间】:2018-11-05 23:17:10
【问题描述】:
我必须构建的函数旨在将字符串中的数字替换为(数字的值 * 下一个字符)。
所以,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?的任何人的参考
【问题讨论】:
标签: python string python-3.x substring