美文网首页
[Python]f字符串

[Python]f字符串

作者: VanJordan | 来源:发表于2019-06-08 22:04 被阅读0次
    • f是格式化字符串,是python3.6以后引进的一个新的特性。一个用法是:
    rules = {f"<oov-{i}>": "UNK" for i in range(10)}
    
    • 感觉可以代替.format
    f"evaluation/hyps/{name}_{checkpoint}_preds.txt"
    
    • 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'
    
    • 控制精度
    >>> a = 123.456
    >>> f'a is {a:8.2f}'
    'a is   123.46'
    >>> f'a is {a:08.2f}'
    'a is 00123.46'
    >>> f'a is {a:8.2e}'
    'a is 1.23e+02'
    >>> f'a is {a:8.2%}'
    'a is 12345.60%'
    >>> f'a is {a:8.2g}'
    'a is  1.2e+02'
    
    >>> s = 'hello'
    >>> f's is {s:8s}'
    's is hello   '
    >>> f's is {s:8.3s}'
    's is hel     '
    

    相关文章

      网友评论

          本文标题:[Python]f字符串

          本文链接:https://www.haomeiwen.com/subject/kzewxctx.html