Python 字符串格式化输出的3种方式

1.  %  
    print ('我叫%s,
身高%scm'  % (name,height))   ** 传入的值为元组,依次填充

  •     %s :占位符 str()  
  •     %d-:十进制 整数
  •     %x : 十六进制
  •     %f  :浮点型

    指定长度:
         %5d     右对齐,不足左边补空格
        %-5d    - 代表左对齐,不足右边默认补空格
        %05d    右对齐,不足左边补0
      

    浮点数:
            %f   默认是输出6位有效数据, 会进行四舍五入
            指定小数点位数的输出 %.2f---保留小数点后2
            '%4.8f'    4代表整个浮点数的长度,包括小数,只有当字符串的长度大于4位才起作用.不足4位空格补足,可以用%04.8使用0补足空格

      


2. format   
    特性:字符串的format方法

  •     顺序填坑:{} 占位符
print('姓名是 {},年龄是 {}'.format('Tom',20))

输出:
姓名是:Tom,年龄是:20
  •   下标填坑:
print('姓名是:{1},年龄是:{0}'.format(20,'Tom'))

输出:
姓名是:Tom,年龄是:20
  •     变量填坑:'名字是:{name},年龄是:{age}'.format(name ='tom',age = 16)
print('姓名是:{name},年龄是:{age}'.format(name='Tom',age=20))

输出:
姓名是:Tom,年龄是:20

变量中使用
name = Ada
age = 20
print('Name is {name},age is {age}'.format(name=name,age=age))

        {:5} 指定输出长度=5
           
字符串 {:5}--左对齐
            数值     {:5}--右对齐
           使用 > <   可以避免字符串/数值对齐方法不一致
            > 右对齐
            < 左对齐

print('姓名是:{0:*<11}\n年龄是:{1:*>11}'.format('Tom',20))

输出:
姓名是:Tom********
年龄是:*********20

      中间对齐 ^  不足的长度用*表示

print('姓名是:{0:*^11}\n年龄是:{1:*^11}'.format('Tom',20))

输出:
姓名是:****Tom****
年龄是:****20*****


3. 格式化 f''  

    python3.6 后的版本支持
    f'名字是:{name},年龄是:{age}'  

name = 'Tom'
age = 20
print(f'姓名是:{name},年龄是:{age}')

 

### Python 字符串格式化输出方法 Python 提供了多种字符串格式化方式,每种方式都有其特点和适用场景。以下是几种常见的字符串格式化方法及其示例: #### 1. `%` 格式化字符 这是最早的一种字符串格式化方法,在 Python 的早期版本中被广泛使用。通过 `%` 符号可以将变量插入到字符串中的指定位置。 ```python name = "Alice" age = 30 formatted_str = "My name is %s and I am %d years old." % (name, age) print(formatted_str) # 输出: My name is Alice and I am 30 years old. ``` 这种方法简单直观,但在复杂情况下可能会显得不够灵活[^3]。 --- #### 2. `str.format()` 方法 `str.format()` 是一种更为现代的字符串格式化方法,自 Python 2.7 起引入。它允许开发者通过 `{}` 占位符定义模板,并在 `.format()` 方法中传入对应的参数。 基本用法如下: ```python name = "Alice" age = 30 formatted_str = "My name is {} and I am {} years old.".format(name, age) print(formatted_str) # 输出: My name is Alice and I am 30 years old. ``` 还可以通过索引或关键字命名占位符来增强可读性和灵活性: ```python formatted_str_with_index = "{1} is {0} years old.".format(age, name) print(formatted_str_with_index) # 输出: Alice is 30 years old. formatted_str_with_keywords = "Name: {n}, Age: {a}".format(n=name, a=age) print(formatted_str_with_keywords) # 输出: Name: Alice, Age: 30 ``` 这种方式相较于 `%` 更加清晰易懂,适合处理复杂的格式需求[^1]。 --- #### 3. F-string(格式化字符串字面量) F-string 自 Python 3.6 开始引入,是一种简洁高效的字符串格式化工具。它可以将表达式嵌入到字符串中,语法更加直观。 ```python name = "Alice" age = 30 formatted_str = f"My name is {name} and I am {age} years old." print(formatted_str) # 输出: My name is Alice and I am 30 years old. ``` 除了简单的变量替换外,F-string 还支持直接嵌套表达式: ```python price = 49.95 tax_rate = 0.08 total_price = price * (1 + tax_rate) receipt = f"Price: ${price:.2f}\nTax Rate: {tax_rate*100}%\nTotal Price: ${total_price:.2f}" print(receipt) # 输出: # Price: $49.95 # Tax Rate: 8% # Total Price: $53.95 ``` 由于其高效性和易读性,F-string 已成为当前推荐的主要字符串格式化方法[^2]。 --- #### 4. 整数填充与对齐 对于一些特定场合下的格式化需求,比如固定宽度的整数输出或者小数转百分比,也可以利用这些方法完成。 ##### 小数转百分比 ```python percentage = 0.75 formatted_percentage = "%.2f%%" % (percentage * 100) print(formatted_percentage) # 输出: 75.00% # 使用 F-string 实现相同效果 formatted_fstring = f"{percentage * 100:.2f}%" print(formatted_fstring) # 输出: 75.00% ``` ##### 数字补零 ```python for i in range(1, 20): padded_number = "%03d" % i print(padded_number) # 使用 zfill() 方法实现同样功能 padded_number_zfill = str(i).zfill(3) print(padded_number_zfill) ``` --- ### 总结 以上介绍了 Python 中常用的三种字符串格式化方法:`%` 格式化字符、`str.format()` 和 F-string。其中,F-string 因为其简洁性和性能优势逐渐取代其他两种方法,特别是在新项目开发中应优先考虑使用 F-string[^2]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值