python如何打印字符串

原创
admin 22小时前 阅读数 4 #Python

Python中的字符串打印

Python中,打印字符串非常简单,您可以使用print()函数将字符串输出到控制台,以下是一个示例:

定义一个字符串
my_string = "Hello, World!"
打印字符串
print(my_string)

输出:

Hello, World!

您还可以将字符串直接作为print()函数的参数,Python会将其输出到控制台。

打印字符串
print("Hello, World!")

输出:

Hello, World!

您还可以使用字符串格式化来输出更复杂的字符串,以下代码将输出“Hello, World! The current time is: 2023-03-15 10:00:00”。

导入datetime模块
import datetime
定义一个字符串
my_string = "Hello, World! The current time is: {}"
格式化字符串并输出
print(my_string.format(datetime.datetime.now()))

输出:

Hello, World! The current time is: 2023-03-15 10:00:00

在格式化字符串时,您可以使用花括号{}来定义占位符,然后使用format()函数将变量或表达式填充到占位符中。

热门