一日一技:python中的 f-string用法.

Python中的 f-string用法.

Python f-string是執行字符串格式化的最新Python語法。 自Python 3.6起可用。 Python f字符串提供了一種更快,更易讀,更簡明且不易出錯的在Python中格式化字符串的方式。

f-string帶有f前綴,並使用{}花括號來評估值.

在冒號後面指定用於類型,填充或對齊的格式說明符; 例如:f'{price:.3}',其中price是變量名。


Python字符串格式化

我們先新建一個formatting_strings.py文件,寫入:

<code>name = 'Peter'
age = 23

print('%s is %d years old' % (name, age))
print('{} is {} years old'.format(name, age))
print(f'{name} is {age} years old')/<code>

執行結果為:

<code>Peter is 23 years old
Peter is 23 years old
Peter is 23 years old/<code>

三條打印結果是等效的。


Python f-string表達式,新建一個expressions.py文件:寫入:

<code>bags = 3
apples_in_bag = 12

print(f'There are total of {bags * apples_in_bag} apples')/<code>

輸出為:

<code>There are total of 36 apples/<code>


Python f-string字典,新建一個dicts.py文件,寫入:


<code>user = {'name': 'John Doe', 'occupation': 'gardener'}

print(f"{user['name']} is a {user['occupation']}")/<code>

結果為:

<code>John Doe is a gardener/<code>


Python多行 f-string,新建一個multiline.py文件,寫入:

<code>name = 'John Doe'
age = 32
occupation = 'gardener'

msg = (
    f'Name: {name}\n'
    f'Age: {age}\n'
    f'Occupation: {occupation}'
)

print(msg)/<code>

執行結果為:

<code>Name: John Doe
Age: 32
Occupation: gardener/<code>


Python f-string 調用函數,新建一個call_function.py文件,寫入:

<code>def mymax(x, y):

    return x if x > y else y

a = 3
b = 4

print(f'Max of {a} and {b} is {mymax(a, b)}')/<code>

執行結果為:

<code>Max of 3 and 4 is 4/<code>


Python f-string 對象,新建一個objects.py文件,寫入:


<code>class User:
    def __init__(self, name, occupation):
        self.name = name
        self.occupation = occupation

    def __repr__(self):
        return f"{self.name} is a {self.occupation}"

u = User('John Doe', 'gardener')

print(f'{u}')/<code>

執行結果:

<code>John Doe is a gardener/<code> 


Python f-string 轉義字符,新建一個escaping.py文件,寫入:

<code>print(f'Python uses {{}} to evaludate variables in f-strings')
print(f'This was a \'great\' film')/<code>

執行結果為:

<code>Python uses {} to evaludate variables in f-strings
This was a 'great' film/<code>


Python f-string中的日期時間格式化,新建一個format_datetime.py文件,寫入:

<code>import datetime

now = datetime.datetime.now()

print(f'{now:%Y-%m-%d %H:%M}')/<code>

輸出結果為:

<code>2020-04-29 22:39/<code>


Python f-string 中格式化浮點數,新建一個format_floats.py文件,寫入:

<code>val = 12.3

print(f'{val:.2f}')
print(f'{val:.5f}')/<code>

輸出結果為:

<code>12.30
12.30000/<code>


Python f-string 格式化寬度,新建一個format_width.py文件,寫入:

<code>for x in range(1, 11):
    print(f'{x:02} {x*x:3} {x*x*x:4}')/<code>

輸出結果為:

<code>01   1    1
02   4    8
03   9   27
04  16   64
05  25  125
06  36  216
07  49  343
08  64  512
09  81  729
10 100 1000/<code>


Python f-string中對齊字符串,新建一個justify.py文件,寫入:

<code>s1 = 'a'
s2 = 'ab'
s3 = 'abc'
s4 = 'abcd'

print(f'{s1:>10}')
print(f'{s2:>10}')
print(f'{s3:>10}')
print(f'{s4:>10}')/<code>

輸出結果為:

<code>         a
        ab
       abc
      abcd/<code>


Python f-string中的數字符號,新建一個format_notations.py文件,寫入:

<code>a = 300

# 十六進制
print(f"{a:x}")

# 八進制
print(f"{a:o}")

#科學計數法
print(f"{a:e}")/<code>

輸出結果為:

<code>12c
454
3.000000e+02/<code>

希望對大家有用,歡迎閱讀與轉發,謝謝!


分享到:


相關文章: