在实际编写代码的过程中,我们时常会遇字符串的拼接,在次列出如下几种常见的拼接方式:
1、加号('+')
print('hello' + 'world' + '!')
#helloworld!
2、逗号,但是字符件会多出来一个空格
print('hello' , 'world' , '!')
#hello world !
3、直接连接
此种连接方式是python独有的,只把两个字符连在一起,中间有无空格无影响,自动连接为一个字符串
print('hello' 'world' '!')
#helloworld!
print('hello''world''!')
#helloworld!
4、格式化(“%”、“format”)
类似于C语言中的printf()函数,格式化连接一般有两种方式,一种为“%”连接,一种为“fromat”连接。
这两种方式分别用符号“%”、“{}”连接一个字符串和一组变量,字符串中的特殊标记会被自动用右边变量组中的变量替换。
4.1 "%"格式化连接
print('%s world !' % ('hello'))
#hello world !
print('PI = %f' % (3.1415926))
#PI = 3.141593
4.2“format”格式化连接
print('{} world !'.format('hello'))
#hello world !
print('PI = {}' .format (3.1415926))
#PI = 3.1415926
5、join连接
join()通过传入一个列表,依次将列表中的每一个元素拼接为字符串;但是join()前面可以加上特定字符,从而会导致串接的字符串出现:列表中每个元素间也会出现相同的特定字符,具体如下:
list = ['hello', 'world', '!']
print(''.join(list))
print(' '.join(list))
print('.'.join(list))
#helloworld!
#hello world !
#hello.world.!
6、多行字符串拼接()
str = (
'hello'
' '
'world'
'!'
)
print(str)
#hello world!