python的f-string 格式化字符串
生活随笔
收集整理的這篇文章主要介紹了
python的f-string 格式化字符串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
f-string
格式化字符串常量(formatted string literals),是Python3.6新引入的一種字符串格式化方法,該方法源于PEP 498 – Literal String Interpolation,主要目的是使格式化字符串的操作更加簡便。f-string在形式上是以 f 或 F 修飾符引領的字符串(f'xxx' 或 F'xxx'),以大括號 {} 標明被替換的字段;f-string在本質上并不是字符串常量,而是一個在運行時運算求值的表達式:
f-string在功能方面不遜于傳統的%-formatting語句和str.format()函數,同時性能又優于二者,且使用起來也更加簡潔明了,因此對于Python3.6及以后的版本,推薦使用f-string進行字符串格式化。
簡單使用
>>> name = 'Eric' >>> f'Hello, my name is {name}' 'Hello, my name is Eric'>>> number = 7 >>> f'My lucky number is {number}' 'My lucky number is 7'>>> price = 19.99 >>> f'The price of this book is {price}' 'The price of this book is 19.99'表達式求值與函數調用
f-string的大括號 {} 可以填入表達式或調用函數,Python會求出其結果并填入返回的字符串內:
>>> f'A total number of {24 * 8 + 4}' 'A total number of 196'>>> f'Complex number {(2 + 2j) / (2 - 3j)}' 'Complex number (-0.15384615384615388+0.7692307692307692j)'>>> name = 'ERIC' >>> f'My name is {name.lower()}' 'My name is eric'>>> import math >>> f'The answer is {math.log(math.pi)}' 'The answer is 1.1447298858494002'多行f-string
f-string還可用于多行字符串:>>> name = 'Eric' >>> age = 27 >>> f"Hello!" \ ... f"I'm {name}." \ ... f"I'm {age}." "Hello!I'm Eric.I'm 27." >>> f"""Hello! ... I'm {name}. ... I'm {age}.""" "Hello!\n I'm Eric.\n I'm 27."自定義格式:對齊、寬度、符號、補零、精度、進制等
f-string采用 {content:format} 設置字符串格式,其中 content 是替換并填入字符串的內容,可以是變量、表達式或函數等,format 是格式描述符。采用默認格式時不必指定 {:format},如上面例子所示只寫 {content} 即可。
總結
以上是生活随笔為你收集整理的python的f-string 格式化字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MongoEngine MongoDB
- 下一篇: python 消息队列、异步分布式