您当前的位置: 首页 >  Python

Xavier Jiezou

暂无认证

  • 2浏览

    0关注

    394博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Python】字符串拼接最常用的五种方法

Xavier Jiezou 发布时间:2021-08-28 20:55:52 ,浏览量:2

文章目录
  • 引言
  • 用法
    • +😀
    • f-strings😀
    • join😀
    • format😐
    • %😐
  • 总结

引言

本文通过实例展示 Python 字符串拼接最常用的五种方法。

用法 +😀
>>> a = 'hello'
>>> b = 'world'
>>> c = a + b
>>> c
'helloworld'
>>> a += b
>>> a
'helloworld'
f-strings😀
>>> a = 'hello'
>>> b = 'world'
>>> c = f'{a} {b}'
>>> c
'hello world'
join😀
>>> a = 'hello'
>>> b = 'world'
>>> c = ','.join([a, b])
>>> c
'hello,world'
>>> d = '-'.join([a, b])
>>> d
'hello-world'
format😐
>>> a = 'hello'
>>> b = 'world'
>>> c = '{a} {b}'.format(a=a, b=b)
>>> c
'hello world'
%😐 符号类型%s字符串%d整数%f浮点数
>>> a = 3
>>> b = 2
>>> c = 1.5 
>>> d = '%d / %d = %.1f' % (a, b, c)
>>> d
'3 / 2 = 1.5'
总结
  • +:最常用的拼接方法,适合字符串变量的简单拼接
  • f-strings:最灵活、方便的拼接方法,适合字符串变量及常量的复杂拼接
  • join:适合字符串列表的拼接
  • format:不推荐使用,可以用 f-strings 替代
  • %:适合熟悉 C 语言的用户使用
关注
打赏
1661408149
查看更多评论
立即登录/注册

微信扫码登录

0.0402s