2012-05-03 83 views
22

我想了解用一些其他文本替换字符串子字符串的最佳方法。这里有一个例子:用Python替换字符串的子字符串

我有一个字符串,一个,可能是像“你好,我的名字是$名称”。我还有另一个字符串b,我想在子字符串'$ name'的位置插入到字符串a中。

我认为这将是最容易的,如果可替换的变量指示某种方式。我使用了美元符号,但它可能是花括号之间的字符串,或者您认为最好的方式。

解决方案: 这是我决定如何做到这一点:

from string import Template 


message = 'You replied to $percentageReplied of your message. ' + 
    'You earned $moneyMade.' 

template = Template(message) 

print template.safe_substitute(
    percentageReplied = '15%', 
    moneyMade = '$20') 
+1

我想问一下重新使用标准格式的方法如果替代品$格式不unchangeble为{ } –

回答

55

以下是最常见的方式做到这一点:

>>> import string 
>>> t = string.Template("Hello my name is $name") 
>>> print t.substitute(name='Guido') 
Hello my name is Guido 

>>> t = "Hello my name is %(name)s" 
>>> print t % dict(name='Tim') 
Hello my name is Tim 

>>> t = "Hello my name is {name}" 
>>> print t.format(name='Barry') 
Hello my name is Barry 

使用string.Template是简单易学,应该熟悉来砸用户的方法。它适合暴露给最终用户。这种风格在Python 2.4中可用。

percent-style对于很多来自其他编程语言的人来说都很熟悉。有些人认为这种风格很容易出错,因为%(name)s中的尾随“s”,因为% - 操作符与乘法具有相同的优先级,并且因为应用参数的行为取决于它们的数据类型(元组和字典get特殊处理)。这种风格从一开始就受到Python的支持。

curly-bracket style仅在Python 2.6或更高版本中受支持。它是最灵活的风格(提供一组丰富的控制字符并允许对象实现自定义格式化程序)。

+16

@kwikness - 我很确定雷蒙德暗指[Guido van Rossum](http://en.wikipedia.org/wiki/Guido_van_Rossum)(pyth关于创作者和BDFL(仁慈的生活独裁者)), Tim Peters([TimSort](http://en.wikipedia.org/wiki/Timsort)fame,写道[Python of Zen](http://stackoverflow.com)/questions/228181/the-zen-of-python))和[Barry Warsaw](http://barry.warsaw.us/)(在python/jython中很大 - 例如在这个[愚人笑话](http ://www.python.org/dev/peps/pep-0401/)巴里叔叔变成了FLUFL(终身友好的语言叔叔)。 –

8

结帐在python替换()函数。这里是一个链接:

http://www.tutorialspoint.com/python/string_replace.htm

试图取代已指定一些文本时,这应该是有用的。例如,在链路他们告诉你这一点:

str = "this is string example....wow!!! this is really string" 
print str.replace("is", "was") 

对于每一个字"is",它会用这个词"was"更换。

+3

这实际上是一个很好的例子,说明为什么str.replace是*不是* OP所需要的:“this”将变成“thwas”:) (请不要分号分号谢谢) –

11

有很多方法可以做到这一点,更常用的是通过字符串已经提供的设施。这意味着使用%运营商,或更好的是,更新的和推荐的str.format()

例子:

a = "Hello my name is {name}" 
result = a.format(name=b) 

或者更简单地说

result = "Hello my name is {name}".format(name=b) 

您还可以使用位置参数:

result = "Hello my name is {}, says {}".format(name, speaker) 

或者有明确的指标:

result = "Hello my name is {0}, says {1}".format(name, speaker) 

,它允许您更改在字符串中的字段的顺序不改变调用format()

result = "{1} says: 'Hello my name is {0}'".format(name, speaker) 

格式真的很强大。您可以使用它来决定制作字段的宽度,如何编写数字以及其他格式,具体取决于您在括号内编写的内容。

如果替换更复杂,您也可以使用str.replace()函数或正则表达式(来自re模块)。

2

您也可以使用%格式化,但.format()被认为更现代。

>>> "Your name is %(name)s. age: %(age)i" % {'name' : 'tom', 'age': 3} 
'Your name is tom' 

但它也支持从平常%格式已知的某些类型检查:

>>> '%(x)i' % {'x': 'string'} 

Traceback (most recent call last): 
    File "<pyshell#40>", line 1, in <module> 
    '%(x)i' % {'x': 'string'} 
TypeError: %d format: a number is required, not str