>>str2="two">>>str1+str2'onetwo'>>>二.格式化字符串连接s" />
Python连接字符串的8种方法汇总 您所在的位置:网站首页 字符串操作函数python Python连接字符串的8种方法汇总

Python连接字符串的8种方法汇总

2024-07-08 17:55| 来源: 网络整理| 查看: 265

推荐简单实用方法: 一、str1+str2 二、格式化连接 三、jion连接

一. str1+str2

string 类型 ‘+’号连接

>>> str1="one" >>> str2="two" >>> str1+str2 'onetwo' >>> 二. 格式化字符串连接

string 类型格式化连接

常见的格式化方式 >>> str1="one" >>> str2="two" >>> "%s%s"%(str1,str2) 'onetwo' 高级点的 format 格式化 >>> "{test}_666@{data:.2f}".format(test="Land", data=10.1) '[email protected]' 鲜为人知的【%(word)type】print 函数格式化 >>> print "%(test)s666%(last)d" % {"test": "Land", "last": 101} Land666101 三. join 方式连接

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

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

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

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

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

>>> list1 ['a', 'b', 'c'] >>> "".join(list1) 'abc' >>> type("".join(list1)) >>> 四. str1 str2

string 类型空格自动连接

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

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

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

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

>>> str1="one" >>> str2="two" >>> str1 ,str2 ('one', 'two') >>> type((str1 ,str2)) >>> 六. str1 \ str2 \str3

string 类型反斜线多行连接

>>> test = "str1 " \ ... "str2 " \ ... "str3" >>> test 'str1 str2 str3' >>> 七. Mstr1N

string 类型乘法连接

>>> str1="one" >>> 1*str1*4 'oneoneoneone' >>> 八. 列表推导方式连接

与 join 方式类似

>>> "".join(["Land" for i in xrange(3)]) 'LandLandLand' >>> "0".join(["Land" for i in xrange(2)]) 'Land0Land' >>>


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有