理论上的生命---史前巨肥猫 2022-04-02 15:05 采纳率: 95.6%
浏览 26
已结题

python中的字符串格式化是什么?

谢谢!

python中的字符串格式化是什么?为什么要做呢?
python中的字符串格式化是什么?为什么要做呢?

  • 写回答

1条回答 默认 最新

  • ~白+黑 Python领域新星创作者 2022-04-02 15:38
    关注
    
    执行字符串格式化操作。调用此方法的字符串可以包含字符串字面值或者以花括号 {} 括起来的替
    换域。每个替换域可以包含一个位置参数的数字索引,或者一个关键字参数的名称。返回的字符串
    副本中每个替换域都会被替换为对应参数的字符串值。
    >>> "The sum of 1 + 2 is {0}".format(1+2)
    'The sum of 1 + 2 is 3'
    
    >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
    'a, b, c'
    >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
    'a, b, c'
    >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
    >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
    'c, b, a'
    >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
    'abracadabra'
    >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-
    ,→ 115.81W')
    'Coordinates: 37.24N, -115.81W'
    >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
    >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
    'Coordinates: 37.24N, -115.81W'
    访问参数的属性:
    >>> c = 3-5j
    >>> ('The complex number {0} is formed from the real part {0.real} '
    ... 'and the imaginary part {0.imag}.').format(c)
    'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part␣
    ,→ -5.0.'
    >>> class Point:
    ... def __init__(self, x, y):
    ... self.x, self.y = x, y
    ... def __str__(self):
    ... return 'Point({self.x}, {self.y})'.format(self=self)
    ...
    >>> str(Point(4, 2))
    'Point(4, 2)'
    访问参数的项:
    >>> coord = (3, 5)
    >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
    'X: 3; Y: 5'
    替代 %s 和 %r:
    >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
    "repr() shows quotes: 'test1'; str() doesn't: test2"
    对齐文本以及指定宽度:
    >>> '{:<30}'.format('left aligned')
    'left aligned '
    >>> '{:>30}'.format('right aligned')
    ' right aligned'
    >>> '{:^30}'.format('centered')
    ' centered '
    >>> '{:*^30}'.format('centered') # use '*' as a fill char
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 4月10日
  • 已采纳回答 4月2日
  • 创建了问题 4月2日

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000