Python格式化字符串的简单方法

Python格式化字符串的简单方法

Python有三种格式化字符串的方式:

  1. %-格式化
  2. str.format()
  3. f-Strings,超级好用

1. %-格式化

name = "北山啦"
age = 18
"%s. am %s years old " %(name, age)

2. str.format()

# 替换字段用大括号进行标记
"hello, {}. you are {}?".format(name,age)
'hello, hoxis. you are 18?'
  • 可以通过索引来以其他顺序引用变量
"hello, {1}. you are {0}?".format(age,name)
'hello, hoxis. you are 18?'
# 使用key-value的键值对
"hello, {name}. you are {age1}?".format(age1=age,name=name)
'hello, hoxis. you are 18?'
# 直接从字典读取数据
person = {
    
    "name":"hoxis","age":18}
"hello, {name}. you are {age}?".format(**person)
'hello, hoxis. you are 18?'
# 依然会比较冗长
"hello, {}. you are {} ?. Your country is {}, and your hair is {}".format(name, age, country,hair)
'hello, hoxis. you are 18 ?. Your country is China, and your hair is black'

3. f-Strings

从Python3.6引入

# 以f字符开头,大括号直接使用变量
f"hi, {name}, are you {age}"
'hi, hoxis, are you 18'
# 直接在大括号里执行计算
f"{ 2 * 3 + 1}"
'7'
# 直接调用函数
test = lambda x : x.lower()
name = "Hoxis"
f"{test(name)} is handsome."
'hoxis is handsome.'
# 直接调用内置函数
f"{name.lower()} is handsome."
'hoxis is handsome.'
# 注意1:如果包含大括号,需要写多个
f"{
    
    {74}}"

猜你喜欢

转载自blog.csdn.net/qq_45176548/article/details/112755288