2020-10-25
阅读量:
852
Python 字符串连接的七种方式
1、’+’ 号连接
>>> text1 = "Hello">>> text2 = "World">>> text1 + text2 'HelloWorld'1234
2、’,’连接成 tuple (元组)类型
Python 中用 ‘,’连接字符串,最终会变成 tuple 类型,代码如下:
>>> text1 = "Hello">>> text2 = "World">>> text1 , text2 ('Hello','World')>>> type((text1, text2)) <type 'tuple'> >>>1234567
3、%s 占位符连接
这种功能比较强大,借鉴了C语言中 printf 函数的功能,如果你有C语言基础,看下文档就知道了。这种方式用符号“%”连接一个字符串和一组变量,字符串中的特殊标记会被自动用右边变量组中的变量替换:
>>> text1 = "Hello">>> text2 = "World">>> "%s%s"%(text1,text2)'HelloWorld'1234
4、空格自动连接
>>> "Hello" "Nasus"'HelloNasus'12
值得注意的是,不能直接用参数代替具体的字符串,否则报错,代码如下:
>>> text1="Hello">>> text2="World">>> text1 text2 File "<stdin>", line 1 text1 text2 ^ SyntaxError: invalid syntax1234567
5、’*’ 连接
这种连接方式就是相当于 copy 字符串,代码如下:
>>> text1="nasus ">>> text1*4'nasus nasus nasus nasus '>>>1234
6、join 连接
利用字符串的函数 join。这个函数接受一个列表或元组,然后用字符串依次连接列表中每一个元素:
>>> list1 = ['P', 'y', 't', 'h', 'o', 'n']>>> "".join(list1)'Python'>>>>>> tuple1 = ('P', 'y', 't', 'h', 'o', 'n')>>> "".join(tuple1)'Python'1234567
每个字符之间加 “|”
>>> list1 = ['P', 'y', 't', 'h', 'o', 'n']>>> "|".join(list1)'P|y|t|h|o|n'123
7、 多行字符串拼接 ()
Python 遇到未闭合的小括号,自动将多行拼接为一行,相比三个引号和换行符,这种方式不会把换行符、前导空格当作字符。
>>> text = ('666' '555' '444' '333')>>> print(text)666555444333>>> print (type(text)) <class 'str'>






评论(0)


暂无数据
推荐帖子
0条评论
0条评论
0条评论