Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

字符串格式化


Python使用C风格的字符串格式化来创建新的格式化字符串。“%”操作符用于格式化一个包含在“元组”(固定大小列表)中的变量集合,以及一个格式字符串,格式字符串包含普通文本和“参数说明符”,如“%s”和“%d”的特殊符号。

假设你有一个名为“name”的变量,其中包含你的用户名,然后你希望打印出对该用户的问候。

# 这会打印出 "Hello, John!"
name = "John"
print("Hello, %s!" % name)

要使用两个或更多参数说明符,请使用元组(括号):

# 这会打印出 "John is 23 years old."
name = "John"
age = 23
print("%s is %d years old." % (name, age))

任何不是字符串的对象也可以使用%s操作符进行格式化。该对象的“repr”方法返回的字符串将被格式化为字符串。例如:

# 这会打印出: A list: [1, 2, 3]
mylist = [1,2,3]
print("A list: %s" % mylist)

以下是一些您应该知道的基本参数说明符:

%s - 字符串(或任何具有字符串表示形式的对象,如数字)

%d - 整数

%f - 浮点数

%.<数字>f - 固定小数位数的浮点数

%x/%X - 十六进制表示的整数(小写/大写)

练习

你将需要编写一个格式字符串,使用以下语法打印出数据: Hello John Doe. Your current balance is $53.44.

data = ("John", "Doe", 53.44) format_string = "Hello" print(format_string % data) data = ("John", "Doe", 53.44) format_string = "Hello %s %s. Your current balance is $%s." print(format_string % data) #test_output_contains("Hello John Doe. Your current balance is $53.44.", no_output_msg= "Make sure you add the `%s` in the correct spaces to the `format_string` to meeet the exercise goals!") test_object('format_string') success_msg('Great work!')

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy