Python中字符串拼接常用的方法!

  在学习和应用Python语言的过程中,我们经常会遇到字符串拼接的问题,其实不管是Python还是其他语言,都把字符串列为最基础和最不可或缺的数据类型,拼接字符串也是必备的一项技能,那么Python语言如何实现这个操作呢?以下是详细的内容:

  1、加号法

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

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

  2、逗号法

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

  str_a = 'python'

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

  输出

  hello python !

  3、直接拼接法

扫描二维码关注公众号,回复: 16244960 查看本文章

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

  #code

  print('abc''xyz')

  #output

  adcxyz

  4、格式化法

  使用%或者format进行拼接

  >>> text1 = "Hello"

  >>> text2 = "World"

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

  'HelloWorld'

  5、join函数法

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

  website = ''.join(listStr)

  6、多行字符串拼接法

  >>> text = ('666'

  '555'

  '444'

  '333')

  >>> print(text)

  666555444333

  >>> print (type(text))

猜你喜欢

转载自blog.csdn.net/oldboyedu1/article/details/132299147
今日推荐