zoukankan      html  css  js  c++  java
  • Python的字符串格式化

    前言

    在 Python 3.6 之前,字符串格式化方法主要有两种:

    • %格式化
    • str.format()

    在Python 3.6 之前,提供了一种新的字符串格式化方法:

    • f-strings

      其比其他格式化方式更易读,更简洁,更不容易出错,而且它们也更快!

    %格式化

    % 格式化方法从 Python 刚开始时就一直存在了

    一般使用方式,要插入多个变量的话,必须使用元组:

    name = "hoxis" 
    age = 18 
    print("hello, %s. you are %s ?" %(name, age))
    
    >>> 'hello, hoxis. you are 18 ?'
    

    这种格式化并不是很好,因为它很冗长并且容易导致错误,比如没有正确显示元组或字典。

    str.format()

    Python 2.6 中引入了 str.format() 格式化方法

    str.format() 是对 %格式化 的改进,它使用普通函数调用语法,并且可以通过 format() 方法为对象进行扩展。

    使用 str.format() 时,替换字段用大括号进行标记:

    # 替换字段用大括号进行标记
    print("hello, {}. you are {}?".
          name,age))
    >>> 'hello, hoxis. you are 18?'
    
    # 通过索引来以其他顺序引用变量
    print("hello, {1}. you are {0}?".format(age,name))
    >>> 'hello, hoxis. you are 18?'
    
    # 通过参数来以其他顺序引用变量
    print("hello, {name}. you are {age1}?".format(age1=age,name=name))
    >>> 'hello, hoxis. you are 18?'
    
    # 从字典中读取数据时还可以使用 **
    person = {"name":"hoxis","age":18}
    print("hello, {name}. you are {age}?".format(**person))
    'hello, hoxis. you are 18?'
    

    在处理多个参数和更长的字符串时仍然可能非常冗长

    f-Strings

    f-strings 是指以 f 或 F 开头的字符串,其中以 {} 包含的表达式会进行值替换。

    name = 'hoxis'
    age = 18
    print(f"hi, {name}, are you {age}")
    >>> 'hi, hoxis, are you 18'
    print(F"hi, {name}, are you {age}")
    >>> 'hi, hoxis, are you 18'
    print(f"{ 2 * 3 + 1}")
    >>> 7
    

    调用函数

    def test(input):
    	return input.lower()
    
    name = "Hoxis"
    print(f"{test(name)} is handsome.")
    >>>'hoxis is handsome.'
    

    也可以直接调用内置函数:

    print(f"{name.lower()} is handsome.")
    >>>'hoxis is handsome.'
    

    特殊符号处理

    • 引号的处理

    可以在字符串中使用各种引号,只要保证和外部的引号不重复即可。

    以下使用方式都是没问题的:

    print(f"{'hoxis'}")
    >>> 'hoxis'
    
    print(f'{"hoxis"}')
    >>> 'hoxis'
    
    print(f"""hoxis""") 
    >>> 'hoxis'
    
    print(f'''hoxis''' )
    >>> 'hoxis'
    

    那如果字符串内部的引号和外部的引号相同时呢?那就需要 进行转义:

    print(f"You are very "handsome"")
    >>> 'You are very "handsome"'
    
    • 括号的处理

    若字符串中包含括号 {},那么你就需要用双括号包裹它:

    print(f"{{74}}")
    >>> '{74}'
    
    print(f"{{{74}}}")
    >>> '{74}'
    

    可以看出,使用三个括号包裹效果一样。

    当然,你可以继续增加括号数目,看下有什么其他效果:

    print(f"{{{{74}}}}")
    >>> '{{74}}'
    
    print(f"{{{{{74}}}}}")
    >>> '{{74}}'
    
    print(f"{{{{{{74}}}}}}")
    >>> '{{{74}}}'
    

    重点:两对为一组

    • 反斜杠

    上面说了,可以用反斜杠进行转义字符,但是不能在 f-string 表达式中使用:

    print(f"You are very "handsome"" )
    >>> 'You are very "handsome"'
    
    print(f"{You are very "handsome"}")
    >>> 报错
    
    # 你可以先在变量里处理好待转义的字符,然后在表达式中引用变量:
    name = '"handsome"' 
    print(f'{name}')
    >>>'"handsome"'
    
    • 注释符号

    不能在表达式中出现 #,否则会报出异常;

    print(f"Hoxis is handsome # really")
    >>> 'Hoxis is handsome # really'
    
    print(f"Hoxis is handsome {#really}")
    >>> 报错
    
  • 相关阅读:
    [LeetCode 1029] Two City Scheduling
    POJ 2342 Anniversary party (树形DP入门)
    Nowcoder 106 C.Professional Manager(统计并查集的个数)
    2018 GDCPC 省赛总结
    CF 977 F. Consecutive Subsequence
    Uva 12325 Zombie's Treasure Chest (贪心,分类讨论)
    Poj 2337 Catenyms(有向图DFS求欧拉通路)
    POJ 1236 Network of Schools (强连通分量缩点求度数)
    POJ 1144 Network (求割点)
    POJ 3310 Caterpillar(图的度的判定)
  • 原文地址:https://www.cnblogs.com/stream886/p/10474652.html
Copyright © 2011-2022 走看看