Python中何时使用%r而不是%s?
在Python中,%r和%s用作字符串格式化操作符,用于将值插入字符串。
%s操作符用于表示字符串,而%r用于表示字符串的原始形式,包括引号和特殊字符。
当您想以用户友好的方式显示字符串,无需任何额外的引号或特殊字符时,请使用%s。
当您想显示变量的精确字符串表示形式,包括它可能包含的任何引号或特殊字符时,请使用%r。
在大多数情况下使用%s,因为它提供了更易于阅读和理解的用户友好输出。
以下是一些说明其区别的示例
示例
在第一种情况下,%s用于将name和age的值插入字符串,从而生成一个格式化的字符串,其中值表示为字符串。
在第二种情况下,使用%r代替,它以原始形式插入name和age的值,包括name字符串值周围的引号。
# Using %s name = 'John' age = 30 print("My name is %s and I am %s years old." % (name, age)) # Using %r name = 'John' age = 30 print("My name is %r and I am %r years old." % (name, age))
输出
My name is John and I am 30 years old. My name is 'John' and I am 30 years old.
以下是一些进一步说明%s和%r字符串格式化操作符之间区别的示例
使用%s和%r处理浮点数
示例
在此示例中,%s和%r都按原样显示number的浮点值。
number = 3.14159 print("The value of pi is approximately %s." % number) print("The value of pi is approximately %r." % number)
输出
The value of pi is approximately 3.14159. The value of pi is approximately 3.14159.
使用%s和%r处理布尔值
示例
在此示例中,%s将is_raining的布尔值显示为字符串('True'),而%r则以其原始形式显示('True')。
is_raining = True print("It is %s that it's raining outside." % is_raining) print("It is %r that it's raining outside." % is_raining)
输出
It is True that it's raining outside. It is True that it's raining outside.
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
使用%s和%r处理列表
示例
在此示例中,%s将列表fruits显示为字符串,而%r则以其原始形式显示,包括每个元素周围的方括号和引号。
fruits = ['apple', 'banana', 'orange'] print("My favorite fruits are: %s." % fruits) print("My favorite fruits are: %r." % fruits)
输出
My favorite fruits are: ['apple', 'banana', 'orange']. My favorite fruits are: ['apple', 'banana', 'orange'].
以下三个示例演示了Python中%s和%r字符串格式化操作符之间的区别
使用%s和%r处理整数
示例
在此示例中,%s和%r都按原样显示number的整数值。
number = 42 print("The answer to life, the universe, and everything is %s." % number) print("The answer to life, the universe, and everything is %r." % number)
输出
The answer to life, the universe, and everything is 42. The answer to life, the universe, and everything is 42.
使用%s和%r处理字符串
示例
在此示例中,%s按原样显示name的字符串值,而%r则用引号将其括起来以指示它是一个字符串。
name = "Alice" print("Hello, my name is %s." % name) print("Hello, my name is %r." % name)
输出
Hello, my name is Alice. Hello, my name is 'Alice'.
使用%s和%r处理字典
示例
在此示例中,%s使用字符串格式化语法显示字典值,而%r则显示原始字典表示形式,包括键和值周围的花括号和引号。
person = {'name': 'Bob', 'age': 30} print("My name is %(name)s and I am %(age)s years old." % person) print("My name is %(name)r and I am %(age)r years old." % person)
输出
My name is Bob and I am 30 years old. My name is 'Bob' and I am 30 years old.
通常,当您想将值格式化为字符串时,应使用%s;当您想将值格式化为原始表示形式时,应使用%r。以下是一些您可能需要使用其中一种或另一种情况。
需要注意的是,Python中还有其他字符串格式化操作符可用,例如f-字符串和format()方法。始终选择适合当前情况的字符串格式化操作符是一个好主意,以确保代码易于阅读和维护。
因此,总而言之,当您想插入一个字符串值时,应使用%s;当您想以其原始形式插入一个值时,应使用%r。