Python常见的字符串格式化

本文介绍了Python中常用的四种字符串格式化方法:%运算符、format()函数、f-string以及str.format_map(),并提到了str.format()的格式指定功能。

Python中字符串格式化有多种方式,以下是其中常用的几种:

  1. 使用%进行格式化:类似于C语言中的printf方式。

    name = "Alice"
    age = 11
    message = "Hello, %s! You are %d years old." % (name, age)
    print(message)
    
  2. 使用format()方法进行格式化:使用大括号{}作为占位符。

    name = "Bob"
    age = 45
    message = "Hello, {}! You are {} years old.".format(name, age)
    print(message)
    
  3. 使用f-string进行格式化(Python 3.6及以上版本支持):在字符串前加上f,然后使用大括号{}包围变量名或表达式。

    name = "Charlie"
    age = 14
    message = f"Hello, {name}! You are {age} years old."
    print(message)
    
  4. 使用str.format_map()方法进行格式化:将格式化参数作为字典传递。

    person = {'name': 'David', 'age': 11}
    message = "Hello, {name}! You are {age} years old.".format_map(person)
    print(message)
    
  5. 使用str.format()方法指定格式:可以指定格式化输出的样式,如小数点后保留几位等。

    price = 45.143333
    formatted_price = "The price is {:.2f} dollars.".format(price)
    print(formatted_price)
    

以上是一些常见的字符串格式化方式,具体使用哪种方式取决于个人偏好和需求。
还有哪些常用的字符串格式化方式是本文没有提到的,还请不吝赐教,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值