2024-09-29 18:55:19 发布
网友
如何在空格中添加字符/数字,如下所示:
Today the ---- is cloudy, but there is no ----. Today the --a)-- is cloudy, but there is no --b)--.(desired result)
如您所见,空格没有被固定字符替换,这使得使用pythonreplace()方法对我来说很复杂。你知道吗
replace()
您可以使用re.sub()。它允许您使用一个函数作为替换,因此该函数可以在每次调用时递增字符。我把函数写成了一个生成器。你知道吗
re.sub()
import re def next_char(): char = 'a' while True: yield char char = chr(ord(char) + 1) if char > 'z': char = 'a' seq = next_char() str = 'Today the is cloudy, but there is no .' str = re.sub(r' ', lambda x: (' ' + next(seq) + ') '), str) print(str)
DEMO
您可以使用
re.sub()
。它允许您使用一个函数作为替换,因此该函数可以在每次调用时递增字符。我把函数写成了一个生成器。你知道吗DEMO
相关问题 更多 >
编程相关推荐