1 """
2 Pytyon字符串拼接的各种方式
3 """
4
5 #1、 %
6 str1="hello"
7 str2="world"
8 str="%s %s"%(str1,str2)
9 print(str)
10
11 #2、 + 两个变量必须是字符串,如果不是要用str(str2)进行转换,不然会报错
12 str1="hello"
13 str2="world"
14 #str2=22
15 str=str1+str2
16 print(str)
17
18 #3、 f-string Python 3.6中引入了
19 str1="hello"
20 str2="world"
21 str=f"{str1} {str2}"
22 print(str)
23
24 #4、 format
25 str1="hello"
26 str2="world"
27 str="{} {}".format(str1,str2)
28 print(str)
29
30 #5、 join
31 arr=["hello","world"]
32 str=" ".join(arr)
33 print(str)
34
35 #6、 * 字符串copy
36 str1="hello world! "
37 str=str1*3
38 print(str)
39
40
41 #7、 \ 多行拼接
42 str="hello "\
43 "world"\
44 "!"
45 print(str)
46
47 #8、() 多行拼接
48 str=(
49 "hello"
50 " "
51 "world"
52 "!")
53 print(str)
54
55 #9、 template 注意str=temp.safe_substitute(a,b)这种方式是不可行的
56 from string import Template
57 a="hello"
58 b="world"
59 temp = Template("${str1} ${str2}!")
60 str=temp.safe_substitute(str1=a,str2=b)
61 print(str)
62
63 #10、 , 只能用于print,赋值等操作会生成元组
64 str1="hello"
65 str2="world"
66 print(str1,str2)
67
68 #11、 直接拼接 不能用变量,没有什么用
69 str='hello' ' world'
70 print(str)
71 str='hello''world'
72 print(str)