• 技术文章 >Python技术 >Python基础教程

    python拼接字符串的方法有哪些?

    小妮浅浅小妮浅浅2021-02-22 09:39:37原创3228

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    1.跟ruby类似

    def func(a):
      b = 'hello'
      return f'{b}, {a}'
     
    >>> func("bbb")
    'hello, bbb'

    这样是不是很干净,跟ruby很类似。

    2.print

    >>> a = '111'
    >>> print(f'hello, {a}')
    hello, 111

    3. 使用template

    >>> from string import Template
    >>> t = Template('Hello, $a!')
    >>> t.substitute(a='world')
    'Hello, world!'

    4.直接连接中间有无空格均可

    print('hello'         ' world')
    print('hello''world')

    5.使用%操作符

    Python 2.6 以前,% 操作符是唯一一种格式化字符串的方法,它也可以用于连接字符串。

    print('%s %s' % ('hello', 'world'))

    今天对于python拼接字符串方法的拓展到这里就结束了,有时候我们也可以选择不常用的方法拼接字符串,说不定会有意外惊喜。

    专题推荐:python拼接字符串
    品易云
    上一篇:python中format的默认下标要求 下一篇:python filter函数的返回值是什么

    相关文章推荐

    • 什么是python字符串的反转?• 如何使用python字符串的str.format函数• 如何将Python字符串生成PDF?• 普通字符如何在python字符串中转义?• 如何实现python字符串反转?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网