迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

在 Python 中打印字符串中的布尔值

作者:迹忆客 最近更新:2022/11/03 浏览次数:

使用格式化的字符串文字来打印字符串中的布尔值,例如 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

Python 打印字符串中的布尔值

我们使用格式化的字符串文字来打印在字符串中存储布尔值的变量。

格式化字符串文字 (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

python print always returns 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

python TypeError can only concatenate str

加法 (+) 运算符左侧和右侧的值需要是兼容的类型。

要解决此问题,需要将布尔值转换为字符串并将两个字符串连接起来。

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

Python 中type函数打印字符串中的布尔值

type 函数返回对象的类型。

如果传入的对象是传入类的实例或子类,则 isinstance 函数返回 True

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便