Python格式化字符串,这个方法你值得拥有!

  一堆堆的烂数据里面有很多的字符串,老是会用到格式化字符串。一般Python 格式化字符串方法有 "%"操作符、format两种,今天要推荐的是第三种方法——formatted string literals。

  ①第一种是上古时代的方法,Python2.6 以前独霸天下的 " % "操作符

name = 'a'
age = 'b'
sex = 'c'
like = 'd'
country = 'e'
print('Hello, my name is %s, %s years old, from %s, sex is %s, like %s.'%(name, age, country, sex, like))

运行结果:Hello, my name is a, b years old, from e, sex is c, like d.

  这种方法当变量多的时候,使用起来会很麻烦。

  ②第二种是 'format '。Python2.6 引入,性能比 % 更强大。大概有三种写法:

  • a) 替换字段直接用大括号
name = 'a'
age = 'b'
sex = 'c'
like = 'd'
country = 'e'
print('Hello, my name is {}, {} years old, from {}, sex is {}, like {}.'.format(name, age, country, sex, like))

运行结果:Hello, my name is a, b years old, from e, sex is c, like d.

  • b) 通过大括号 + 索引引用变量
name = 'a'
age = 'b'
sex = 'c'
like = 'd'
country = 'e'
print('Hello, my name is {1}, {0} years old, from {3}, sex is {2}, like {4}.'.format(age, name, sex, country, like))

运行结果:Hello, my name is a, b years old, from e, sex is c, like d.

  代码中{1}索引的是name,{0}索引的是age,{2}索引的是sex,{3}索引的是country,{4}索引的是like。

  • c) 使用键值对的方式
name = 'a'
age = 'b'
sex = 'c'
like = 'd'
country = 'e'
print('Hello, my name is {name}, {age} years old, from {country}, sex is {sex}, like {like}.'.format(age = age, name = name, sex = sex, country = country, like = like))

运行结果:Hello, my name is a, b years old, from e, sex is c, like d.

  这种方法format的大括号和变量名是分开的,当变量多的时候,使用起来会很容易把人搞晕。

  ③第三种是formatted string literals。它是在 Python3.6 新加的字符串格式化方法,这种方法是在字符串前面加上 “f”,大括号直接使用变量,所以又叫 ‘f-strings’。

name = 'a'
age = 'b'
sex = 'c'
like = 'd'
country = 'e'
print(f'Hello, my name is {name}, {age} years old, from {country}, sex is {sex}, like {like}.')

运行结果:Hello, my name is a, b years old, from e, sex is c, like d.

  它还可以进行内联运算,也就是大括号里面还可以写算术表达式:
  >>> f’{1 + 2 + 3}’
  ‘6’

  它还可以直接调用函数:
  >>>name = ‘A’
  >>> f’ {name.lower()}’
  ’ a’

  相比于 ‘%’ 和 ‘format’,f-string 的性能更好,运行速度更快,如果你的 Python 是 3.6 及以上的,非常建议用 f-string!
  更多用法详见Formatted string literals的官方文档。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值