【python】函数print

函数print

name = "John"
age = 30
print("My name is", name, "and I am", age, "years old.")

输出:

My name is John and I am 30 years old.

 

>>> name = "Eric"
>>> "Hello, %s." % name
'Hello, Eric.'

 

f-string 

python 中的字符串通常被括在双引号("")或单引号('')内。要创建 f-string,你只需要在字符串的开头引号前添加一个 f 或 F。例如,"This" 是一个字符串,而 f"This" 是一个 f-string。当使用 f-string 来显示变量时,你只需要在一组大括号 {} 内指定变量的名字。而在运行时,所有的变量名都会被替换成它们各自的值。语法如下所示:

author = "jane smith"
a_name = author.title()
print(f"This is a book by {a_name}.")

输出:

 

This is a book by Jane Smith.

 

{!r} 是 Python 中的一种格式化字符串方式,它可以将一个变量以其对应的 Python 表示形式(representation)替换到字符串中。例如:

name = "Alice"
age = 30
print("My name is {!r} and I'm {!r} years old.".format(name, age))

输出:

My name is 'Alice' and I'm 30 years old.

在上面的例子中,{!r} 将会把变量 nameage 分别替换为其对应的字符串表示形式。name 的字符串表示是 "Alice",因此在输出字符串中会被包裹在单引号内;age 的字符串表示是整数 30,因此不需要加引号。

参考资料

1. Python 3's f-Strings: An Improved String Formatting Syntax (Guide)

posted @ 2023-06-03 22:53  苏格拉底的落泪  阅读(122)  评论(0编辑  收藏  举报