在 Python 中打印字符串中的布尔值
使用格式化的字符串文字来打印字符串中的布尔值,例如 print(f'is subscribed: {my_bool}')
。 格式化的字符串字面量让我们通过在字符串前面加上 f 来将变量包含在字符串中。
my_bool = True
result = f'is subscribed: {my_bool}'
print(result) # 👉️ is subscribed: True
my_bool_2 = False
result = f'{my_bool} is the opposite of {my_bool_2}'
print(result) # 👉️ True is the opposite of False
我们使用格式化的字符串文字来打印在字符串中存储布尔值的变量。
格式化字符串文字 (f-strings)
让我们通过在字符串前面加上 f 来在字符串中包含表达式。
my_str = 'is subscribed:'
my_bool = True
result = f'{my_str} {my_bool}'
print(result) # 👉️ is subscribed: True
我们可以根据需要使用这种方法在字符串中插入尽可能多的用于存储布尔值的变量。
确保将表达式包裹在花括号 - {expression}
中。
请注意,print()
函数返回 None,因此不要尝试将调用 print
的结果存储在变量中。
my_bool = True
# ⛔️ BAD (print always returns None)
result = print(f'is subscribed: {my_bool}')
print(result) # 👉️ None
相反,将值存储在变量中并将变量传递给 print()
函数。
my_bool = True
result = f'is subscribed: {my_bool}'
print(result) # 👉️ is subscribed: True
使用格式化字符串文字的替代方法是将多个逗号分隔的参数传递给 print()
函数。
# 👇️ is subscribed: True
print('is subscribed:', True)
# 👇️ is subscribed:True
print('is subscribed:', True, sep='')
默认情况下,当我们将多个逗号分隔的参数传递给
print()
函数时,它们会被空格分隔。
我们可以将 sep
关键字参数设置为空字符串以删除分隔符。
注意
,我们不应尝试在 bool 和 str 类型的值之间使用加法 (+
) 运算符。
my_bool = True
my_str = 'is subscribed: '
# ⛔️ TypeError: can only concatenate str (not "bool") to str
result = my_str + my_bool
加法 (
+
) 运算符左侧和右侧的值需要是兼容的类型。
要解决此问题,需要将布尔值转换为字符串并将两个字符串连接起来。
my_bool = True
my_str = 'is subscribed: '
result = my_str + str(my_bool)
print(result) # 👉️ is subscribed: True
我们使用 str()
类将布尔值转换为字符串,因此我们可以连接两个字符串并打印结果。
如果我们不确定变量存储什么类型,请使用内置的 type()
类。
my_str = 'is subscribed:'
print(type(my_str)) # 👉️ <class 'str'>
print(isinstance(my_str, str)) # 👉️ True
my_bool = True
print(type(my_bool)) # 👉️ <class 'bool'>
print(isinstance(my_bool, bool)) # 👉️ True
type
函数返回对象的类型。
如果传入的对象是传入类的实例或子类,则 isinstance
函数返回 True。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。