温馨提示×

Python print的进阶用法

小樊
87
2024-06-24 23:37:29
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

  1. 格式化输出 可以使用格式化字符串来输出变量的值。例如,可以使用%s来表示字符串,%d来表示整数等。示例如下:
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
  1. 多个参数打印 print函数可以接受多个参数,并以空格分隔输出。示例如下:
name = "Bob"
age = 30
print("My name is", name, "and I am", age, "years old.")
  1. 使用sep参数指定分隔符 可以使用sep参数指定多个参数之间的分隔符。示例如下:
name = "Charlie"
age = 35
print("My name is", name, "and I am", age, "years old.", sep='---')
  1. 使用end参数指定行尾符 可以使用end参数指定输出的行尾符,默认值是换行符。示例如下:
name = "David"
age = 40
print("My name is", name, "and I am", age, "years old.", end=' ')
print("This is on the same line.")
  1. 格式化输出数字 可以使用format函数来格式化输出数字。示例如下:
num = 3.14159
print("The value of pi is {:.2f}.".format(num))
  1. 使用f-string f-string是Python3.6引入的一种新的字符串格式化方法,可以直接在字符串前面加上f来表示。示例如下:
name = "Eve"
age = 45
print(f"My name is {name} and I am {age} years old.")

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Python中setattr函数的进阶用法有哪些

0