分享

一文秒懂!Python字符串格式化之format方法详解

 流形sbz 2023-10-15 发布于甘肃

format是字符串内嵌的一个方法,用于格式化字符串。以大括号{}来标明被替换的字符串,一定程度上与%目的一致。但在某些方面更加的方便

1、基本用法

1、按照{}的顺序依次匹配括号中的值

  1. s = '{} is a {}'.format('Tom''Boy')
  2. print(s) # Tom is a Boy
  3. s1 = '{} is a {}'.format('Tom')
  4. # 抛出异常, Replacement index 1 out of range for positional args tuple
  5. print(s1)

2、通过索引的方式去匹配参数

这里需要注意的是,索引从0开始计算。

  1. s = '{0} is a {1}'.format('Tom''Boy')
  2. print(s) # Tom is a Boy
  3. s1 = '{1} is a {2}'.format('Tom''Lily''Girl')
  4. print(s1) # Lily is a Girl

字符串中索引的顺序可以打乱,并不影响匹配。

  1. s = '{1} is a {0}'.format('Boy''Tom', )
  2. print(s) # Tom is a Boy

3、通过参数名来匹配参数

  1. s = '{name} is a {sex}'.format(name='Tom', sex='Boy')
  2. print(s) # Tom is a Boy

同理,如果参数已经确定,可以直接利用{}进行格式化引用。

  1. name = 'Tom'
  2. sex = 'Girl'
  3. # 以f开头表示在字符串中支持大括号内的python表达式
  4. s = f'{name} is a {sex}'
  5. print(s) # Tom is a Boy

4、混搭使用

可以通过索引,参数名来混搭进行匹配。

  1. s = 'My name is {}, i am {age} year old, She name is {}'.format('Liming''Lily', age=10)
  2. print(s) # My name is Liming, i am 10 year old, She name is Lily

需要注意的是,命名参数必须写道最后。负责会编译报错!

  1. s = 'My name is {}, i am {age} year old, She name is {}'.format('Liming', age=10'Lily')
  2. print(s)  # SyntaxError: positional argument follows keyword argument

另外,不可以索引和默认格式化混合使用。

  1. s = '{} is a {0}'.format('Boy''Tom', )
  2. print(s)
  3. s1 = '{} is a {1}'.format('Boy''Tom', )
  4. print(s1)

以上两种写法均报异常。

# ValueError: cannot switch from automatic field numbering to manual field specification

2、进阶用法

1、支持对参数部分引用

可以通过索引对参数的部分进行取值。如下:s[0] = w。

  1. s = 'The word is {s}, {s[0]} is initials'.format(s='world')
  2. # The word is world, w is initials
  3. print(s)

2、数字的处理

普通的直接匹配数字没什么好说的,与基础部分的字符串匹配一样。

  1. s = 'π is {}'.format(3.1415926)
  2. print(s) # π is 3.1415926

如何使用format 保留两位小数呢?需要使用:.2f,在用%进行格式化时我们使用的是%:.2f

  1. s = 'π is {:.2f}'.format(3.1415926)
  2. print(s) # π is 3.14
  3. s1 = 'π is %.2f'3.1415926
  4. print(s1) # π is 3.14

同时这种方法还可以用于字符串截取,不过数字后面就不能加f了。

  1. s = '{:.1}'.format('Hello')
  2. print(s) # H 

给数字加千位符

  1. s = '{:,}'.format(1000000)
  2. print(s) # 1,000,000

将数字转换成二进制

  1. s = '{:b}'.format(8)
  2. print(s) # 1000

将数字转换成八进制

  1. s = '{:o}'.format(8)
  2. print(s) # 10

将数字转换成十六进制

  1. s = '{:X}'.format(12)
  2. print(s) # C

总结如下

  • b: 输出整数的二进制方式;

  • c: 输出整数对应的 Unicode 字符;

  • d: 输出整数的十进制方式;

  • o: 输出整数的八进制方式;

  • x: 输出整数的小写十六进制方式;

  • X: 输出整数的大写十六进制方式;

3、格式处理

通过:+数字指定转换后的字符串长度,不足的部分用空格补充

  1. s = '{:2}b'.format('a')
  2. print(s) # a b  (a后面补了一个空格)
  3. # 如果指定的长度小于参数的长度,按照原参数匹配
  4. s1 = '{:2}World'.format('Hello')
  5. print(s1) # HelloWorld

4、字符的填充

可通过:符号^数字进行字符串的填充。其中数字为填充后的字符串总长度。

  1. s = '{:*^10}'.format('Hello')
  2. print(s) # **Hello***
  3. s = '{:-^20}'.format('123456')
  4. print(s) # -------123456-------

如果数字小于字符串的长度,则不进行填充操作。

  1. s = '{:*^3}'.format('Hello')
  2. print(s) # Hello

5、list、tuple的拆分

在format格式化时,可使用* 或者 ** 进行对list、tuple拆分。

  1. foods = ['fish''beef''fruit']
  2. s = 'i like eat {} and {} and {}'.format(*foods)
  3. # i like eat fish and beef and fruit
  4. print(s)
  1. foods = ['fish''beef''fruit']
  2. s = 'i like eat {2} and {0} and {1}'.format(*foods)
  3. # i like eat fruit and fish and beef
  4. print(s)
  1. dict_temp = {'name''Lily''age'18
  2. # 字典需要用 ** 进行拆分
  3. s = 'My name is {name}, i am {age} years old'.format(**dict_temp)
  4. print(s) # My name 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多