• 技术文章 >常见问题 >Python常见问题

    python中如何实现字符串拼接?

    宋雪维宋雪维2020-12-24 14:36:31原创6645

    小编介绍过python中字符串分割的三种方法(https://www.py.cn/faq/python/22312.html),既然有分割,那也会有拼接。本文主要向大家介绍Python中实现分割的6种方法:1、加号法;2、逗号法;3、直接拼接法;4、格式化法;5、join函数法;6、多行字符串拼接法。详情请看本文。

    1、加号法

    使用简单直接,但这种方法效率低

    1

    website  =  'python'  'tab'  '.com'

    2、逗号法

    字符串之间会多出一个空格

    1

    2

    str_a = 'python'

    print('hello', str_a, '!')

    输出

    1

    hello python !

    3、直接拼接法

    Python独有拼接法,只能用于字符串的拼接,不能用于变量拼接

    1

    2

    3

    4

    5

    #code

    print('abc''xyz')

      

    #output

    adcxyz

    4、格式化法:使用%或者format进行拼接

    1

    2

    3

    4

    >>> text1 = "Hello"

    >>> text2 = "World"

    >>> "%s%s"%(text1,text2)

    'HelloWorld'

    5、join函数法

    1

    2

    listStr  =  [ 'python' 'tab' '.com' ]

    website  =  ''.join(listStr)

    6、多行字符串拼接法

    1

    2

    3

    4

    5

    6

    7

    8

    >>> text = ('666'

     '555'

     '444'

     '333')

    >>> print(text)

    666555444333

    >>> print (type(text))

    <class 'str'>

    以上就是Python字符串拼接的常见六种方法,大家可以根据个人需求选择不同方法拼接,大家可以直接套用哦~

    专题推荐:python字符串拼接?
    上一篇:如何比较python字符串大小? 下一篇:python中extend()方法如何实现列表合并?

    相关文章推荐

    • python sorted中key参数怎么用?• python json模块是什么?• 如何使用python any()判断多元素?• python delattr函数如何使用?• 如何使用python raise抛出异常?

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网