• python 字符串格式化


    1. 使用%

    1.1 按位置格式化:

    name = 'jack'
    age = 18
    text = '我是%s, 年龄%s岁' %(name, age)
    print(text)
    print('我是%s, 年龄%s岁' %('rose', 16))
    
    • 1
    • 2
    • 3
    • 4
    • 5

    这里的%s是为字符串占位,而真正为整型占位的是%d,严谨的方式写:text = '我是%s, 年龄%d岁' %(name, age)

    1.2 按名称格式化

    text = '我是%(name)s, 我叫%(name)s, 年龄:%(age)s岁' %{'name': 'jack', 'age': 12}
    print(text)
    
    • 1
    • 2

    1.3 需要注意的是

    text = '%s的GDP要提升40%' %'中国'
    print(text)
    
    • 1
    • 2

    上面这段代码会运行出错:

    Traceback (most recent call last):
      File "c:\Users\vincent\Desktop\code\neimeng-python\test\test_str.py", line 12, in <module>
        text = '%s的GDP要提升40%' %'中国'
    ValueError: incomplete format
    
    • 1
    • 2
    • 3
    • 4

    因为我们的字符串中出现了多个%,会把%也当做了占位符,因此报错。

    解决这种方式的方法就是多写一个%,例如:

    text = '%s的GDP要提升40%%' %'中国'
    print(text)
    
    • 1
    • 2

    因此,一旦字符串中存在百分比的形式,一定要加两个%以实现百分比的效果。

    2. format

    方式1:

    text = '我叫{0}, 今年{1}岁, 我是{0}'.format('tom', 16)
    print(text)
    
    • 1
    • 2

    方式2:
    也可以不写序号,默认则是按位置来取对应的值,但是上面的情况则会报错:

    text = '我叫{}, 今年{}岁'.format('tom', 16)
    print(text)
    
    • 1
    • 2

    方式3:

    text = '我叫{name}, 今年{age}岁'.format(name='tom', age=16)
    print(text)
    
    • 1
    • 2

    可以把上面的字符串赋值给变量,下面这种形式本质上跟上面是一样的。

    text = '我叫{name}, 今年{age}岁'
    print(text.format(name='tom', age=16))
    
    text = '我是%(name)s, 我叫%(name)s, 年龄:%(age)s岁'
    print(text %{'name': 'jack', 'age': 12})
    
    • 1
    • 2
    • 3
    • 4
    • 5

    f格式化

    Python3.6版本及之后才支持的方式。

    name = 'tom'
    age = '19'
    text = f'我叫{name}, 今年{age}岁'
    
    • 1
    • 2
    • 3

    可以支持表达式:

    name = 'jerry'
    age = 7
    text = f'我叫{name}, 今年{age+1}岁'
    print(text)
    
    • 1
    • 2
    • 3
    • 4

    在Python3.8引入的新功能:

    name = 'jerry'
    age = 7
    text = f'我叫{name}, 今年{age+1 =}岁'
    print(text)
    
    • 1
    • 2
    • 3
    • 4

    输出结果:我叫jerry, 今年age+1=8岁

    进制转换:

    # 转化为二进制
    print(f'今年{22: #b}岁') # 今年 0b10110岁
    # 转化为八进制
    print(f'今年{22: #o}岁')  # 今年 0o26岁
    # 转化为十六进制
    print(f'今年{22: #x}岁')  # 今年 0x16岁
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    可以执行函数:

    name = 'jerry'
    text = f'我是{name.upper()}'
    print(text) # 会把name变成大写
    
    • 1
    • 2
    • 3
  • 相关阅读:
    nginx端口映射后,跳转带的是内网端口而不是内网端口
    Zebec 生态 AMA 回顾:Nautilus 以及 $ZBC 的未来
    四大直辖市1米分辨率土地覆盖数据,精度超高
    使用Vitis HLS生成 IP核 (verilog版和图形化版)
    电子器件系列53:D型触发器
    Java--SpringBoot使用@Transactional注解添加事务
    一种通过udp进行无确认ip的双向的通信
    QT调用OpenCV绘制直线、矩形、椭圆、圆、不规则曲线、文本
    PerfView专题 (第十三篇):洞察 .NET程序 的非托管句柄泄露
    MATLAB学习笔记(系统学习)
  • 原文地址:https://blog.csdn.net/vincent_duan/article/details/125502256