Python格式化字符串的简单方法
        【摘要】     Python格式化字符串的简单方法 
Python有三种格式化字符串的方式: 
%-格式化str.format()f-Strings,超级好用 
1. %-格式化 
name = "北山啦"
age = 18
12 
"%s. am %s years old " %(name, age)
1 
2. str.format() 
# 替换字段用大括号进行标记
"hello...
    
    
    
    Python格式化字符串的简单方法
Python有三种格式化字符串的方式:
- %-格式化
- str.format()
- f-Strings,超级好用
1. %-格式化
name = "北山啦"
age = 18
  
 - 1
- 2
"%s. am %s years old " %(name, age)
  
 - 1
2. str.format()
# 替换字段用大括号进行标记
"hello, {}. you are {}?".format(name,age)
  
 - 1
- 2
'hello, hoxis. you are 18?'
  
 - 1
- 可以通过索引来以其他顺序引用变量
"hello, {1}. you are {0}?".format(age,name)
  
 - 1
'hello, hoxis. you are 18?'
  
 - 1
# 使用key-value的键值对
"hello, {name}. you are {age1}?".format(age1=age,name=name)
  
 - 1
- 2
'hello, hoxis. you are 18?'
  
 - 1
# 直接从字典读取数据
person = {"name":"hoxis","age":18}
"hello, {name}. you are {age}?".format(**person)
  
 - 1
- 2
- 3
'hello, hoxis. you are 18?'
  
 - 1
# 依然会比较冗长
"hello, {}. you are {} ?. Your country is {}, and your hair is {}".format(name, age, country,hair)
  
 - 1
- 2
'hello, hoxis. you are 18 ?. Your country is China, and your hair is black'
  
 - 1
3. f-Strings
从Python3.6引入
# 以f字符开头,大括号直接使用变量
f"hi, {name}, are you {age}"
  
 - 1
- 2
'hi, hoxis, are you 18'
  
 - 1
# 直接在大括号里执行计算
f"{ 2 * 3 + 1}"
  
 - 1
- 2
'7'
  
 - 1
# 直接调用函数
test = lambda x : x.lower()
name = "Hoxis"
f"{test(name)} is handsome."
  
 - 1
- 2
- 3
- 4
'hoxis is handsome.'
  
 - 1
# 直接调用内置函数
f"{name.lower()} is handsome."
  
 - 1
- 2
'hoxis is handsome.'
  
 - 1
# 注意1:如果包含大括号,需要写多个
f"{{74}}"
  
 - 1
- 2
文章来源: beishan.blog.csdn.net,作者:北山啦,版权归原作者所有,如需转载,请联系作者。
原文链接:beishan.blog.csdn.net/article/details/112755288
        【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
            cloudbbs@huaweicloud.com
        
        
        
        
        
        
        - 点赞
- 收藏
- 关注作者
 
             
           
评论(0)