這篇文章主要介紹“Python中str.format()和f-string如何使用”,在日常操作中,相信很多人在Python中str.format()和f-string如何使用問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Python中str.format()和f-string如何使用”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
string format 有兩種方式:
1.{} 是占位符 ( placeholder ),對應的值在 format() 的括號內。
例如:
print('Hi, {}!'.format('Mary'))
顯示結果為:
Hi, Mary!
2.format() 中可以填入變量,這種方式更常見。例如:
name='Julie' print('Hi, {}!'.format(name))
顯示結果為:
Hi, Julie!
3.還可以有多個變量。例如:
num_apple=6 num_orange=3 print('I bought {} apples and {} oranges.'.format(num_apple,num_orange))
顯示結果為:
I bought 6 apples and 3 oranges.
4.{} 可以設置變量格式,前面要加上 :,其后的數字表示這個整數、或字符串、或小數點后有幾位。例如:
fruit='apples' number=6 price=1.2 print('{:5d} {:8}, price:{:.5f}.'.format(number,fruit,price*number))
顯示結果為:
6 apples , price:7.20000.
從結果可以看到:
(1) 比如 apples 有 6 位,設置格式為 8 位 {:8},結果顯示中 apples 后面有 2 位空格。
(2) format() 中可以傳入變量運算的值,比如例子中的 price*number。
5.{} 中可以加上數字索引,對應的是 format() 中的元素位置。例如:
print('I bought {1} oranges,{0} bananas and {0} apples.'.format(6,3))
顯示結果為:
I bought 3 oranges,6 bananas and 6 apples.
上面的語句中,{0} 對應 format(6,3) 的第一個值 6,{1} 對應第二個值 3。
注:這里既可以用 f'',也可以用 F''。
1.與方式一不同,f'{}'直接在{}寫入變量值。例如:
name='Julie' print(f'{name} is learning Python.')
顯示結果為:
Julie is learning Python.
2.與方式一相同,f'' 也可以設置多個變量。例如:
num_apple=6 num_orange=3 print(f'I bought {num_apple} apples and {num_orange} oranges.')
顯示結果為:
I bought 6 apples and 3 oranges.
3.與方式一相同,{} 中可以設置格式。例如:
fruit='apples' number=6 price=1.2 print(f'{number:5d} {fruit:8}, price:{price*number:.5f}')
顯示結果為:
6 apples , price:7.20000
到此,關于“Python中str.format()和f-string如何使用”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。