【问题标题】:how can I add different character to blank spaces in a string?(or replace specific word in a string with different characters or numbers.)如何向字符串中的空格添加不同的字符?(或用不同的字符或数字替换字符串中的特定单词。)
【发布时间】:2019-07-12 00:12:12
【问题描述】:

我怎样才能像这样在空格中添加字符/数字:

Today the ---- is cloudy, but there is no ----.

Today the --a)-- is cloudy, but there is no --b)--.(desired result)

如您所见,空格不会被固定字符替换,这使得使用 python replace() 方法对我来说很复杂。

【问题讨论】:

  • 您不是在替换空格,而是在替换一串连字符。
  • 你可以使用 for 循环和 if 语句来做到这一点
  • 字符串是不可变的,所以你需要创建新的。也许您可以简单地使用 f 字符串:a = "--a)--"; b = "--b)--"; f"Today the {a} is cloudy, but there is no {b}."
  • 总是连续的字母,abc等?
  • @Alexander 想必要修改的字符串是动态的,而不是文字。

标签: python string replace text-manipulation


【解决方案1】:

您可以使用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

【讨论】:

  • 我得到:SyntaxError: invalid syntax for char = 'a':
  • 去掉最后一行的冒号。 char = 'a'
  • @YusufUMS 谢谢,它似乎返回了字符的地址:'今天 --)-- 多云,但没有 --)--.'.
  • 抱歉,我没有正确调用生成器。我更新了答案并添加了一个可运行的演示
猜你喜欢
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
  • 2020-06-02
  • 1970-01-01
相关资源
最近更新 更多