[英]No return value from function in Python 3? Why do I have to do a = int(a, 16) in Python instead of just int(a)
[英]Why would I use int( input().strip() ) instead of just int( input() ) in Python?
如果我想将数字作为输入,是否还需要.strip()
方法? 像这样:
n = int(input().strip())
而不仅仅是编码:
n = int(input())
我知道.strip()
返回字符串的副本,其中从字符串的开头和结尾删除了所有字符。 但我想知道为什么/是否有必要。
将它转换为带有int
的整数时没有必要,因为int
已经处理(忽略)前导和尾随空格*:
>>> int('1 ')
1
>>> int(' 1')
1
>>> int(' 1\n\t') # also handles other spaces like newlines or tabs
1
如果使用sys.stdin.readline
(包含尾随换行符)并且您不知道使用该值的函数是否可以处理其他空格,则删除空格非常重要。
*仅供参考:该类型的float
, complex
, fractions.Fraction
和decimal.Decimal
也忽略开头和结尾的空格,所以你不需要strip
字符串,如果你使用到这些。
现在您可以使用名为 ninput 的新库并使用名为 int_input() 的函数例如
import ninput
n = ninput.int_input()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.