【问题标题】:Replace part of string in Python-在Python中替换部分字符串-
【发布时间】:2018-01-22 08:22:31
【问题描述】:

我想在 Python 中替换部分字符串。特别是,我想摆脱结构"Hello[hi, ... ,bye]",其中的点代表任意长度的字符。

我发现在How to use string.replace() in python 3.x 中解释了如何使用替换,但我无法弄清楚如何将模式“Hello[hi, ... ,bye]”与任意一段字符串匹配的'...'

示例 1:

text= "Hello.hi[. Hello[hi, my name is alice ,bye] ,bye]"

我要:result= "Hello.hi[., 123 my name is alice 456 ,bye]"

但我希望同样的模式也适用于示例 2:

text= "Hello.hi[., Hello[hi, have a good day ,bye] ,bye]"

我要:result= "Hello.hi[., 123 have a good day 456 ,bye]"

有什么建议吗?谢谢。

【问题讨论】:

标签: python replace


【解决方案1】:

使用replace。

text= "Hello[hi, my name is alice ,bye] "
text.replace('hi,', '123').replace(',bye', '456')
>>> 'Hello[123 my name is alice 456] '

同样适用于“Hello[hi, have a good day,bye]”

【讨论】:

  • 你替换的不够多。应该是:text.replace('Hello[hi,', '123').replace(',bye] ', '456')
  • 您好,感谢您的回答!我已经尝试过了,但我没有得到我想要的。我已经编辑了帖子以使问题更清楚。
  • @yago:我明白了。你绝对应该使用regex (import re) 搜索/替换。请参阅互联网上的手册以将其与 Python 一起使用。
  • @Artur Barseghyan,谢谢!是的,我一直在阅读有关正则表达式的信息,但我是初学者,我还不能解决它,所以我在这里发帖以防有人能启发我。我会继续阅读。再次感谢。
  • @yago:你只想替换左括号和右括号内的单词吗?否则,请让您的问题非常具体。
【解决方案2】:

试试这个,

index_l=[]
x=0
for i in text:
    if i == ',':index_l.append(i)
output = text[index_l[0]:index_l[1]]
print output

【讨论】:

  • 这只会去掉逗号中包含的字符串!
  • 感谢@Ubdus Samad,但这也不起作用,因为我有很多昏迷的大文本。这些例子只是一些句子。我想知道 a 是否可以匹配整个模式 "Hello[hi, ... ,bye]"
  • 那就学习正则表达式吧!
【解决方案3】:

谢谢大家。我已经使用这个帖子Python: Replace string with prefixStringSuffix keeping original case, but ignoring case when searching for match解决了这个问题

解决方案

import re
text="Hello[hi, my name is alice ,bye]"
search = re.compile(r'Hello\[hi,(.*?),bye\]')
a=search.sub('123\\1 456', text)
print(a)

【讨论】:

    猜你喜欢
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 2012-07-17
    相关资源
    最近更新 更多