美文网首页
python 字符串的格式化

python 字符串的格式化

作者: tafanfly | 来源:发表于2018-10-17 18:04 被阅读0次
    • 使用%s作为占用符
    >>> 'Hello, %s' % 'World'
    'Hello, World'
    

    当然还有其他的占用符可以使用, 比如%d(十进制整数), %f(浮点数)等

    >>> 'I am %d years old' % 20
    'I am 20 years old'
    
    >>> 'I am %d year old' % '20'
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
        'I am %d year old' % '20'
    TypeError: %d format: a number is required, not str
    
    >>> 'Pi is %f' % 3.1415
    'Pi is 3.141500'
    
    >>> 'Pi is %.3f' % 3.1415
    'Pi is 3.142'
    
    • 使用{}作为占用符
    >>> 'Hello, {}'.format('World')
    'Hello, World'
    
    >>> 'I {} {} years old'.format('am', 20)
    'I am 20 years old'
    >>> 'I {} {} years old'.format('am', '20')
    'I am 20 years old'
    >>> 'I {am} {age} years old'.format(am='am', age=20)
    'I am 20 years old'
    
    • 字典格式
    >>> 'I am %(age)s' % {'age': 20}
    'I am 20'
    

    相关文章

      网友评论

          本文标题:python 字符串的格式化

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