Python中的字符串替换

时间:2016-05-12 00:53:25

标签: python string python-2.7

想要找到一种优雅的方法,用一组值动态替换xxxxx部分(xxxxx更像是真实字符串值的模板占位符)。例如,如果数组是["foo","goo","zoo"],我想生成3个动态字符串

a="hello values: [xxxxx], have a good day"

预期的动态字符串,

"hello values: [foo], have a good day"
"hello values: [goo], have a good day"
"hello values: [zoo], have a good day"
提前谢谢, 林

6 个答案:

答案 0 :(得分:2)

完美地使用map()即使列表理解是更新,更惯用的方式。

>>> a = "hello values: [{}]"
>>> names = ["foo", "goo", "zoo"]

>>> map(a.format, names)

['hello values: [foo]', 
 'hello values: [goo]', 
 'hello values: [zoo]']

答案 1 :(得分:1)

使用字符串替换功能。

a.replace("xxxxxx", "foo")

列表:

src_name = ["foo", "goo", "zoo"]
a = "hello values: [xxxxx], have a good day"
result = (a.replace("xxxxx", d) for d in src_name)
for i in result:
    print (i)

输出:

hello values: [foo], have a good day
hello values: [goo], have a good day
hello values: [zoo], have a good day

答案 2 :(得分:1)

arr=["foo","goo","zoo"]
a="hello values: [xxxxx], have a good day"
for el in arr:
  print(a.replace("xxxxx",el))

答案 3 :(得分:1)

替换功能是您正在寻找的:

a.replace('xxxxx','stringtoreplace')

如果你想通过数组,那么:

for str in stringarray:
     print(a.replace('xxxxx',str))

答案 4 :(得分:1)

我的第一个意图是:

sentence = "hello values: [xxxxx], have a good day"
names = ["foo", "goo", "zoo"]

sentences = [sentence.replace("xxxxx", name) for name in names]

但我对你的申请有一个难闻的气味......这是一个不寻常的问题。

答案 5 :(得分:0)

我将遍历数组并在其上执行正则表达式。

寻找“[xxxxx]”的模式出现,并用数组值替换它。

你也可以简单地用数组值替换xxx,但这可能是不可靠的,锚定到[xxx]会更加安全,因为它更严格。

Python的正则表达式API。 https://docs.python.org/2/library/re.html