打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python string字符串的7种连接方式
原创 2016年08月09日 12:20:38



  • 以下基于python 2.7版本,代码片段真实有效。

    一. str1+str2

    string类型 ‘+’号连接

    >>> str1="one">>> str2="two">>> str1+str2'onetwo'>>>

    二. str1,str2

    string类型 ‘,’号连接成tuple类型

    >>> str1="one">>> str2="two">>> str1 ,str2('one', 'two')>>> type((str1 ,str2))<type 'tuple'>>>>

    三. “%s%s” %(str1,str2)

    string类型占位符连接

    >>> str1="one">>> str2="two">>> "%s%s"%(str1,str2)'onetwo'

    四. str1 str2

    string类型空格自动连接

    >>> "one" "two"'onetwo'

    这里需要注意的是,参数不能代替具体的字符串写成
    错误方式:

    >>> str1="one">>> str2="two">>> str1 str2  File "<stdin>", line 1    str1 str2            ^SyntaxError: invalid syntax

    五. M*str1*N

    string类型乘法连接

    >>> str1="one">>> 1*str1*4'oneoneoneone'>>>

    六. join方式连接

    string类型join方式连接list/tuple类型

    >>> str1="one">>> list1=["a","b","c"]>>> tuple1=("H","I","J")>>> str1.join(list1)'aonebonec'>>> str1.join(tuple1)'HoneIoneJ'

    这里的join有点像split的反操作,将列表或元组用指定的字符串相连接;
    但是值得注意的是,连接的列表或元组中元素的类型必须全部为string类型,否则就可能报如下的错误:

    >>> list2=["a",2,"c",4.3]>>> str1.join(list2)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: sequence item 1: expected string, int found>>>

    join还有一个妙用,就是将所有list或tuple中的元素连接成string类型并输出;

    >>> list1['a', 'b', 'c']>>> "".join(list1)'abc'>>> type("".join(list1))<type 'str'>>>>

    七.列表推导方式连接

    与join方式类似

    >>> "".join(["Land" for i in xrange(3)])'LandLandLand'>>> "0".join(["Land" for i in xrange(2)])'Land0Land'>>>
    版权声明:本文为博主原创文章,未经博主允许不得转载。

    本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
    打开APP,阅读全文并永久保存 查看更多类似文章
    猜你喜欢
    类似文章
    Python数据分析:基础
    python|typing模块的介绍
    typing库:让你的代码阅读者再也不用猜猜猜
    8种Python字符串拼接的方法,你知道几种?
    python类型转换
    python中数字类型和字符串类型的相互转换的方法
    更多类似文章 >>
    生活服务
    热点新闻
    分享 收藏 导长图 关注 下载文章
    绑定账号成功
    后续可登录账号畅享VIP特权!
    如果VIP功能使用有故障,
    可点击这里联系客服!

    联系客服