Skip to main content
 首页 » 编程设计

python之为什么字符串类型变量在 Python 中被视为 boolean 值

2025年05月04日20itcoder

在下面的代码中:

def modify_note(self): 
    id = input("Enter a note id: ") 
    memo = input("Enter a memo: ") 
    tags = input("Enter tags: ") 
    if memo: 
       self.notebook.modify_memo(id, memo) 
    if tags: 
       self.notebook.modify_tags(id, tags) 

memo 和tags 都是字符串类型的变量。你怎么能在 if 之后写它们,这里 python 是否将它们视为 boolean 值?

请您参考如下方法:

Python 中的每个对象都有一个 truth value .如果字符串非空,则为 True。