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´> <