由于Python的字符串不能更改,我想知道如何更有效地连接字符串?

我可以这样写:

s += stringfromelsewhere

或者像这样:

s = []

s.append(somestring)
    
# later
    
s = ''.join(s)

在写这个问题的时候,我发现了一篇关于这个话题的好文章。

http://www.skymind.com/~ocrow/python_string/

但它在Python 2.x中。,所以问题是Python 3中有什么变化吗?


当前回答

写出这个函数

def str_join(*args):
    return ''.join(map(str, args))

这样你就可以随时随地打电话了

str_join('Pine')  # Returns : Pine
str_join('Pine', 'apple')  # Returns : Pineapple
str_join('Pine', 'apple', 3)  # Returns : Pineapple3

其他回答

写出这个函数

def str_join(*args):
    return ''.join(map(str, args))

这样你就可以随时随地打电话了

str_join('Pine')  # Returns : Pine
str_join('Pine', 'apple')  # Returns : Pineapple
str_join('Pine', 'apple', 3)  # Returns : Pineapple3

如果要连接的字符串是字面量,则使用字符串字面量连接

re.compile(
        "[A-Za-z_]"       # letter or underscore
        "[A-Za-z0-9_]*"   # letter, digit or underscore
    )

如果你想对字符串的一部分进行注释(如上所述),或者如果你想对文本的一部分而不是全部使用原始字符串或三引号,这是非常有用的。

因为这发生在语法层,所以它使用零连接操作符。

我的用例略有不同。我必须构造一个查询,其中超过20个字段是动态的。 我遵循了这种使用格式方法的方法

query = "insert into {0}({1},{2},{3}) values({4}, {5}, {6})"
query.format('users','name','age','dna','suzan',1010,'nda')

这对我来说相对简单,而不是使用+或其他方法

推荐的方法仍然是使用追加和连接。

在Python >= 3.6中,新的f-string是连接字符串的有效方法。

>>> name = 'some_name'
>>> number = 123
>>>
>>> f'Name is {name} and the number is {number}.'
'Name is some_name and the number is 123.'