python 字符串拼接七种方式

1.%方式

%格式化字符串的方式继承自古老的C语言

示例:

print('%s %s' % ('hello', 'world'))
hello world

类似的占位符还有%d(代表整数),%f(代表浮点数),%x(代表十六进制数)

2.format

s1 = 'hello {}! my name is {}'.format('world', 'python')
print(s1)
hello world! my name is python

3.类似元组方式

s_tuple = ('hello', ' ', 'world')
s_like_tuple = ('hello' ' ' 'world')
print(s_tuple)
('hello', ' ', 'world')
print(s_like_tuple)
hello world

4.面向对象模板拼接

from string import Template
s = Template('${s1} ${s2}!')
print(s.safe_substitute(s1='hello', s2='world'))
hello world!

5.常用的+

str_1 = 'hello world!'
str_2 = 'my name is python'
print(str_1 + str_2)
hello world!my name is python

6.join 方法拼接

str_list = ['hello', 'world!']
str_join1 = ' '.join(str_list)
str_join2 = '_'.join(str_list)
print(str_join1)
hello world!
print(str_join2)
hello_world!

7.f-string方式

name = 'world'
myname = 'python_cat'
words = f'hello {name}. my name is {myname}'
print(words)
hello world. my name is python_cat
  • 14
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值