Python 字符串追加

Python 字符串追加

让我们来看一个将字符串 ‘n’ 次连接的函数。

def str_append(s, n):
    output = ''
    i = 0
    while i < n:
        output += s
        i = i + 1
    return output

请注意,我定义这个函数是为了展示 + 运算符的用法。稍后我将使用 timeit 模块来测试性能。如果你只是想要将一个字符串 ‘n’ 次连接,你可以轻松地使用 s = 'Hi' * 10

另一种执行字符串追加操作的方法是创建一个列表,并将字符串追加到列表中。然后使用字符串的 join() 函数将它们合并在一起以获得结果字符串。

def str_append_list_join(s, n):
    l1 = []
    i = 0
    while i < n:
        l1.append(s)
        i += 1
    return ''.join(l1)

让我们测试这些方法,确保它们按预期工作。

if __name__ == "__main__":
    print('使用 + 运算符追加:', str_append('Hi', 10))
    print('使用列表和 join() 追加:', str_append_list_join('Hi', 10))
    # 用下面的方式,上面的方法是为了使用 timeit 模块检查性能
    print('使用 * 运算符追加:', 'Hi' * 10)

输出:

使用 + 运算符追加: HiHiHiHiHiHiHiHiHiHi
使用列表和 join() 追加: HiHiHiHiHiHiHiHiHiHi
使用 * 运算符追加: HiHiHiHiHiHiHiHiHiHi

Python 中追加字符串的最佳方法

我已经在 string_append.py 文件中定义了这两种方法。让我们使用 timeit 模块来检查它们的性能。

$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append("Hello", 1000)' 
1000 loops, best of 5: 174 usec per loop
$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append_list_join("Hello", 1000)'
1000 loops, best of 5: 140 usec per loop

$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append("Hi", 1000)' 
1000 loops, best of 5: 165 usec per loop
$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append_list_join("Hi", 1000)'
1000 loops, best of 5: 139 usec per loop

!python string append, python add to string

总结

如果只有少量字符串,你可以使用任何方法来追加它们。从可读性的角度来看,对于少量字符串,使用 + 运算符似乎更好。然而,如果你需要追加大量字符串,那么你应该使用列表和 join() 函数。

  • 21
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张无忌打怪兽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值