python拼接字符串的方法有哪些?

550次阅读
没有评论
python拼接字符串的方法有哪些?

python拼接字符串的方法有哪些?

1.跟ruby类似

def func(a):
  b = 'hello'
  return f'{b}, {a}'
 
>>> func("bbb")
'hello, bbb'

这样是不是很干净,跟ruby很类似。

2.print

>>> a = '111'
>>> print(f'hello, {a}')
hello, 111

3. 使用template

>>> from string import Template
>>> t = Template('Hello, $a!')
>>> t.substitute(a='world')
'Hello, world!'

4.直接连接中间有无空格均可

print('hello'         ' world')
print('hello''world')

5.使用%操作符

在 Python 2.6 以前,% 操作符是唯一一种格式化字符串的方法,它也可以用于连接字符串。

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

今天对于python拼接字符串方法的拓展到这里就结束了,有时候我们也可以选择不常用的方法拼接字符串,说不定会有意外惊喜。

 

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-30发表,共计501字。
新手QQ群:570568346,欢迎进群讨论 Python51学习