python中字符串的六种连接方式

在实际编写代码的过程中,我们时常会遇字符串的拼接,在次列出如下几种常见的拼接方式:

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!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值