I'd like to get a few opinions on the best way to replace a substring of a string with some other text. Here's an example:
我想就用一些其他文本替换字符串的子串的最佳方法得到一些意见。这是一个例子:
I have a string, a, which could be something like "Hello my name is $name". I also have another string, b, which I want to insert into string a in the place of its substring '$name'.
我有一个字符串,a,可能是“你好我的名字是$ name”。我还有另一个字符串b,我想在其子字符串'$ name'的位置插入字符串a。
I assume it would be easiest if the replaceable variable is indicated some way. I used a dollar sign, but it could be a string between curly braces or whatever you feel would work best.
我认为如果以某种方式指示可替换变量将是最简单的。我使用了一个美元符号,但它可能是花括号之间的字符串或者你觉得最好的效果。
Solution: Here's how I decided to do it:
解决方案:以下是我决定这样做的方法:
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')
6 个解决方案
#1
55
Here are the most common ways to do it:
以下是最常用的方法:
>>> 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
The approach using string.Template is easy to learn and should be familiar to bash users. It is suitable for exposing to end-users. This style became available in Python 2.4.
使用string.Template的方法很容易学习,并且对于bash用户应该很熟悉。它适合暴露给最终用户。这种风格在Python 2.4中可用。
The percent-style will be familiar to many people coming from other programming languages. Some people find this style to be error-prone because of the trailing "s" in %(name)s
, because the %-operator has the same precedence as multiplication, and because the behavior of the applied arguments depends on their data type (tuples and dicts get special handling). This style has been supported in Python since the beginning.
来自其他编程语言的许多人都会熟悉百分比风格。有些人发现这种风格容易出错,因为%(name)s中的尾随“s”,因为%-operator具有与乘法相同的优先级,并且因为应用参数的行为取决于它们的数据类型(元组和词汇得到特殊处理)。 Python从一开始就支持这种风格。
The curly-bracket style is only supported in Python 2.6 or later. It is the most flexible style (providing a rich set of control characters and allowing objects to implement custom formatters).
只有Python 2.6或更高版本支持花括号样式。它是最灵活的样式(提供丰富的控制字符集并允许对象实现自定义格式化程序)。
#2
11
There are a number of ways to do it, the more commonly used would be through the facilities already provided by strings. That means the use of the %
operator, or better yet, the newer and recommended str.format()
.
有很多方法可以做到,通常使用的是通过字符串提供的设施。这意味着使用%运算符,或者更好的是,使用更新和推荐的str.format()。
Example:
a = "Hello my name is {name}"
result = a.format(name=b)
Or more simply
或者更简单
result = "Hello my name is {name}".format(name=b)
You can also use positional arguments:
您还可以使用位置参数:
result = "Hello my name is {}, says {}".format(name, speaker)
Or with explicit indexes:
或者使用显式索引:
result = "Hello my name is {0}, says {1}".format(name, speaker)
Which allows you to change the ordering of the fields in the string without changing the call to format()
:
这允许您更改字符串中字段的顺序而不更改对format()的调用:
result = "{1} says: 'Hello my name is {0}'".format(name, speaker)
Format is really powerful. You can use it to decide how wide to make a field, how to write numbers, and other formatting of the sort, depending on what you write inside the brackets.
格式非常强大。您可以使用它来决定创建字段的宽度,如何编写数字以及排序的其他格式,具体取决于您在括号内写的内容。
You could also use the str.replace()
function, or regular expressions (from the re
module) if the replacements are more complicated.
如果替换更复杂,您还可以使用str.replace()函数或正则表达式(来自re模块)。
#3
#4
8
Checkout the replace() function in python. Here is a link:
在python中查看replace()函数。这是一个链接:
http://www.tutorialspoint.com/python/string_replace.htm
This should be useful when trying to replace some text that you have specified. For example, in the link they show you this:
在尝试替换您指定的某些文本时,这应该很有用。例如,在链接中,他们向您显示:
str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
For every word "is"
, it would replace it with the word "was"
.
对于每个单词“is”,它将用“was”替换它。
#5
5
You can do something like:
你可以这样做:
"My name is {name}".format(name="Name")
It's supported natively in python, as you can see here:
它在python中原生支持,你可以在这里看到:
#6
2
You may also use formatting with % but .format() is considered more modern.
您也可以使用%格式,但.format()被认为更现代。
>>> "Your name is %(name)s. age: %(age)i" % {'name' : 'tom', 'age': 3}
'Your name is tom'
but it also supports some type checking as known from usual % formatting:
但它也支持一些类型检查,如通常的%格式所知:
>>> '%(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
#1
55
Here are the most common ways to do it:
以下是最常用的方法:
>>> 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
The approach using string.Template is easy to learn and should be familiar to bash users. It is suitable for exposing to end-users. This style became available in Python 2.4.
使用string.Template的方法很容易学习,并且对于bash用户应该很熟悉。它适合暴露给最终用户。这种风格在Python 2.4中可用。
The percent-style will be familiar to many people coming from other programming languages. Some people find this style to be error-prone because of the trailing "s" in %(name)s
, because the %-operator has the same precedence as multiplication, and because the behavior of the applied arguments depends on their data type (tuples and dicts get special handling). This style has been supported in Python since the beginning.
来自其他编程语言的许多人都会熟悉百分比风格。有些人发现这种风格容易出错,因为%(name)s中的尾随“s”,因为%-operator具有与乘法相同的优先级,并且因为应用参数的行为取决于它们的数据类型(元组和词汇得到特殊处理)。 Python从一开始就支持这种风格。
The curly-bracket style is only supported in Python 2.6 or later. It is the most flexible style (providing a rich set of control characters and allowing objects to implement custom formatters).
只有Python 2.6或更高版本支持花括号样式。它是最灵活的样式(提供丰富的控制字符集并允许对象实现自定义格式化程序)。
#2
11
There are a number of ways to do it, the more commonly used would be through the facilities already provided by strings. That means the use of the %
operator, or better yet, the newer and recommended str.format()
.
有很多方法可以做到,通常使用的是通过字符串提供的设施。这意味着使用%运算符,或者更好的是,使用更新和推荐的str.format()。
Example:
a = "Hello my name is {name}"
result = a.format(name=b)
Or more simply
或者更简单
result = "Hello my name is {name}".format(name=b)
You can also use positional arguments:
您还可以使用位置参数:
result = "Hello my name is {}, says {}".format(name, speaker)
Or with explicit indexes:
或者使用显式索引:
result = "Hello my name is {0}, says {1}".format(name, speaker)
Which allows you to change the ordering of the fields in the string without changing the call to format()
:
这允许您更改字符串中字段的顺序而不更改对format()的调用:
result = "{1} says: 'Hello my name is {0}'".format(name, speaker)
Format is really powerful. You can use it to decide how wide to make a field, how to write numbers, and other formatting of the sort, depending on what you write inside the brackets.
格式非常强大。您可以使用它来决定创建字段的宽度,如何编写数字以及排序的其他格式,具体取决于您在括号内写的内容。
You could also use the str.replace()
function, or regular expressions (from the re
module) if the replacements are more complicated.
如果替换更复杂,您还可以使用str.replace()函数或正则表达式(来自re模块)。
#3
#4
8
Checkout the replace() function in python. Here is a link:
在python中查看replace()函数。这是一个链接:
http://www.tutorialspoint.com/python/string_replace.htm
This should be useful when trying to replace some text that you have specified. For example, in the link they show you this:
在尝试替换您指定的某些文本时,这应该很有用。例如,在链接中,他们向您显示:
str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
For every word "is"
, it would replace it with the word "was"
.
对于每个单词“is”,它将用“was”替换它。
#5
5
You can do something like:
你可以这样做:
"My name is {name}".format(name="Name")
It's supported natively in python, as you can see here:
它在python中原生支持,你可以在这里看到:
#6
2
You may also use formatting with % but .format() is considered more modern.
您也可以使用%格式,但.format()被认为更现代。
>>> "Your name is %(name)s. age: %(age)i" % {'name' : 'tom', 'age': 3}
'Your name is tom'
but it also supports some type checking as known from usual % formatting:
但它也支持一些类型检查,如通常的%格式所知:
>>> '%(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