格式化字符串时多次插入相同的值

问题:格式化字符串时多次插入相同的值

我有这种形式的字符串

s='arbit'
string='%s hello world %s hello world %s' %(s,s,s)

字符串中的所有%s都具有相同的值(即s)。有没有更好的书写方式?(而不是列出三遍)

I have a string of this form

s='arbit'
string='%s hello world %s hello world %s' %(s,s,s)

All the %s in string have the same value (i.e. s). Is there a better way of writing this? (Rather than listing out s three times)


回答 0

您可以使用Python 2.6和Python 3.x中提供的高级字符串格式

incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)

You can use advanced string formatting, available in Python 2.6 and Python 3.x:

incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)

回答 1

incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}

您可能需要阅读以下内容以了解:String Formatting Operations

incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}

You may like to have a read of this to get an understanding: String Formatting Operations.


回答 2

您可以使用格式的字典类型:

s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}

You can use the dictionary type of formatting:

s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}

回答 3

取决于您的意思更好。如果您的目标是消除冗余,则此方法有效。

s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))

Depends on what you mean by better. This works if your goal is removal of redundancy.

s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))

回答 4

>>> s1 ='arbit'
>>> s2 = 'hello world '.join( [s]*3 )
>>> print s2
arbit hello world arbit hello world arbit
>>> s1 ='arbit'
>>> s2 = 'hello world '.join( [s]*3 )
>>> print s2
arbit hello world arbit hello world arbit

回答 5

弦线

如果您正在使用Python 3.6+,则可以使用新的,f-strings它代表格式化的字符串,可以通过f在字符串的开头添加字符以将其标识为f字符串来使用它

price = 123
name = "Jerry"
print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!")
>Jerry!!, 123 is much, isn't 123 a lot? Jerry!

使用f字符串的主要好处是它们更具可读性,可以更快,并且具有更好的性能:

每个人的熊猫资源:Python数据分析,作者Daniel Y. Chen

基准测试

毫无疑问,新f-strings方法更具可读性,因为您不必重新映射字符串,但是如前所述,它是否更快?

price = 123
name = "Jerry"

def new():
    x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!"


def old():
    x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name)

import timeit
print(timeit.timeit('new()', setup='from __main__ import new', number=10**7))
print(timeit.timeit('old()', setup='from __main__ import old', number=10**7))
> 3.8741058271543776  #new
> 5.861819514350163   #old

运行1000万次测试似乎新f-strings的映射速度实际上更快。

Fstrings

If you are using Python 3.6+ you can make use of the new so called f-strings which stands for formatted strings and it can be used by adding the character f at the beginning of a string to identify this as an f-string.

price = 123
name = "Jerry"
print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!")
>Jerry!!, 123 is much, isn't 123 a lot? Jerry!

The main benefits of using f-strings is that they are more readable, can be faster, and offer better performance:

Source Pandas for Everyone: Python Data Analysis, By Daniel Y. Chen

Benchmarks

No doubt that the new f-strings are more readable, as you don’t have to remap the strings, but is it faster though as stated in the aformentioned quote?

price = 123
name = "Jerry"

def new():
    x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!"


def old():
    x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name)

import timeit
print(timeit.timeit('new()', setup='from __main__ import new', number=10**7))
print(timeit.timeit('old()', setup='from __main__ import old', number=10**7))
> 3.8741058271543776  #new
> 5.861819514350163   #old

Running 10 Million test’s it seems that the new f-strings are actually faster in mapping.