【问题标题】:Why whitespace is not the delimiter for input()?为什么空格不是 input() 的分隔符?
【发布时间】:2014-11-15 22:24:29
【问题描述】:

我是Python 的新手。在 Python 中,input()raw_input() 逐行读取,而在 C/C++ 中,读取输入的默认分隔符是空格。

我知道我可以使用split() 来获取列表。没有空格作为默认输入分隔符有什么意义吗?

【问题讨论】:

    标签: python input delimiter


    【解决方案1】:

    在 Python 2 中,input() 接受来自用户的一行代码,执行它并返回结果——因此逐行而不是逐字阅读的意义在于它使该过程更加容易。 raw_inputinput 的双胞胎,除了它没有尝试评估输入的内容,它只是将其作为 str 返回。

    运行用户输入也很危险,这就是为什么它在 Python 3 中被删除,而raw_input 取代了input

    Python 2

    --> test_var = input('enter a number: ')
    # user enters "71 + 9" (without quotes), Python tries to run the text entered
    --> test_var
    # 80
    --> type(test_var)
    # <type 'int'>
    
    --> test_var = raw_input('enter another number: ')
    # user enters "99 - 9", Python simply gives back the string '99 - 9'
    --> test_var
     # '99 - 9'
    --> type(test_var)
    # <type 'str'>
    
    --> test_var = input('enter something')
    # user enters "howdy" (without the quotes)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1, in <module>
    NameError: name 'howdy' is not defined
    

    【讨论】:

    • 我无法理解“在 Python 2 中,input() 将尝试评估用户输入的文本,而 raw_input() 不会”。如果您不介意,可以简单解释一下吗?
    • @Venkatesh input() 将根据用户输入的内容调用 eval()。因此,如果您输入 22+5input() 将返回 27。另一方面,raw_input() for 22+5 将产生 "22+5"
    • @ArdaXi:谢谢,我也把它放在我的回答中。
    【解决方案2】:

    在 Python 中,输入默认类型为 string,在 string 对象的值中,允许使用空格(例如 s = "Bob Fred")。 split(delim) 用于通过指定的分隔符拆分字符串对象(同样,如果您将 delim 参数留空,则默认分隔符是空格)。

    我认为这是一个默认选择(设计决策),因为您很快就会意识到将字符串转换为整数、浮点数等类型的数据类型非常简单。

    【讨论】:

    • 输入没有“默认类型”的字符串。它总是返回字符串。期间。
    • @NedBatchelder 是的,这是一个设计决策,很可能在未来版本的某个时候发生变化。
    • 不,不会。 raw_input (python 2) / input (python 3) 的重点是返回字符串。我们不会改变这一点。
    • @EthanFurman 很好。我确信这是有充分理由的 - 但这可能是不同的章节。
    猜你喜欢
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 2022-11-17
    • 1970-01-01
    相关资源
    最近更新 更多