【问题标题】:Replacing words tagged by #word# within a string [closed]替换字符串中由#word#标记的单词[关闭]
【发布时间】:2014-07-21 23:15:37
【问题描述】:

我想搜索和替换两个 # 标记之间的单词。

文本是随机的(用户添加)。

例子:

text = "hello this #word1# a it #word2# thanks!"

我需要剪掉# 之间的两个词(word1 和 word2)并将它们更改为标题大小写 - .title()

期望的输出:

"hello this #Word1# a it #Word2# thanks!"

【问题讨论】:

  • 您要在最终文本中保留# 标记,还是删除它们?

标签: python string replace


【解决方案1】:

您可以使用正则表达式来做到这一点:

import re

text = 'hello this #word1# a it #word2# thanks!'
print re.sub('#(\w+)#', lambda m:m.group(1).title(), text)

输出:

你好这个 Word1 a it Word2 谢谢!

编辑

如果要保留边界 # 字符,请使用非捕获表达式:

print re.sub('(?<=#)(\w+)(?=#)', lambda m:m.group(1).title(), text)

输出:

你好这个#Word1# 一个它#Word2# 谢谢!

【讨论】:

  • 怎么做 输出:你好这个 #Word1# a it #Word2# 谢谢!
  • 嗨@user3697586,请参阅上面的编辑!
【解决方案2】:
s = "hello this #word1# a it #word2# thanks!".split()
result = ' '.join([w[1:-1].title() if w[0] == '#' else w for w in s])

给了

'hello this Word1 a it Word2 thanks!'

s = "hello this #word1# a it #word2# thanks!".split()
result = ' '.join([w.title() if w[0] == '#' else w for w in s])    

给了

'hello this #Word1# a it #Word2# thanks!'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 2013-12-28
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多