python 字符串连接

如题所述

python中字符串怎么连接呢?不知道的小伙伴来看看小编今天的分享吧!
python中字符串连接有七种方法。
方法一:用“+”号连接
用 “+”连接字符串是最基本的方式,代码如下。
text1 = Hello
text2 = World
text1 + text2
HelloWorld
方法二:
用“,”连接成 tuple (元组)类型
Python 中用“,”连接字符串,最终会变成 tuple 类型,代码如下:
text1 = Hello
text2 = World
text1 , text2
(Hello,World)
type((text1, text2))
type tuple
方法三:
用%s 占位符连接
%s 占位符连接功能强大,借鉴了C语言中 printf 函数的功能,这种方式用符号“%”连接一个字符串和一组变量,字符串中的特殊标记会被自动用右边变量组中的变量替换:
text1 = Hello
text2 = World
%s%s%(text1,text2)
HelloWorld
方法四:
空格自动连接
Hello Nasus
HelloNasus
值得注意的是,不能直接用参数代替具体的字符串,否则报错,代码如下:
text1=Hello
text2=World
text1 text2
File stdin, line 1
text1 text2
^
SyntaxError: invalid syntax
方法五:
用“*” 连接
这种连接方式就是相当于 copy 字符串,代码如下:
text1=nasus
text1*4
nasus nasus nasus nasus
方法六
:join 连接
利用字符串的函数 join。这个函数接受一个列表或元组,然后用字符串依次连接列表中每一个元素:
list1 = [P, y, t, h, o, n]
.join(list1)
Python
tuple1 = (P, y, t, h, o, n)
.join(tuple1)
Python
每个字符之间加 “|”
list1 = [P, y, t, h, o, n]
|.join(list1)
P|y|t|h|o|n
方法七:
多行字符串拼接 ()
Python 遇到未闭合的小括号,自动将多行拼接为一行,相比三个引号和换行符,这种方式不会把换行符、前导空格当作字符。
text = (666
555
444
333)
print(text)
666555444333
print (type(text))
class str
温馨提示:答案为网友推荐,仅供参考
相似回答