美文网首页
python拼接字符串

python拼接字符串

作者: 二十四桥11 | 来源:发表于2018-01-25 22:39 被阅读0次

    https://www.cnblogs.com/jamsent/p/7183905.html

    fruit1 = 'apples'
    fruit2 = 'bananas'
    fruit3 = 'pears'

    1. 用+符号拼接
      用+拼接字符串如下:

    str = 'There are'+fruit1+','+fruit2+','+fruit3+' on the table'
    该方法效率比较低,不建议使用

    1. 用%符号拼接
      str = 'There are %s, %s, %s on the table.' % (fruit1,fruit2,fruit3)
      除了用元组的方法,还可以使用字典如下:

    str = 'There are %(fruit1)s,%(fruit2)s,%(fruit3)s on the table' % {'fruit1':fruit1,'fruit2':fruit2,'fruit3':fruit3}

    1. 用join()方法拼接
      join()`方法拼接如下

    temp = ['There are ',fruit1,',',fruit2,',',fruit3,' on the table']
    ''.join(temp)
    该方法使用与序列操作

    1. 用format()方法拼接
      用format()方法拼接如下:

    1 str = 'There are {}, {}, {} on the table'
    2 str.format(fruit1,fruit2,fruit3)

    还可以指定参数对应位置:
    str = 'There are {2}, {1}, {0} on the table'
    str.format(fruit1,fruit2,fruit3) #fruit1出现在0的位置

    同样,也可以使用字典:
    str = 'There are {fruit1}, {fruit2}, {fruit3} on the table'
    str.format(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3)

    相关文章

      网友评论

          本文标题:python拼接字符串

          本文链接:https://www.haomeiwen.com/subject/vqibaxtx.html