Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I use int( input().strip() ) instead of just int( input() ) in Python?

Tags:

python

string

int

If I want to take a number as input, would I also need the .strip() method? Like this:

n = int(input().strip())

Instead of just coding:

n = int(input())

I know .strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string. But I wonder why / if it is necessary.

like image 808
capfion Avatar asked Jan 13 '18 18:01

capfion


1 Answers

It isn't necessary when you cast it to an integer with int because int already handles (ignores) leading and trailing whitespaces*:

>>> int('1 ')
1
>>> int(' 1')
1
>>> int(' 1\n\t')  # also handles other spaces like newlines or tabs
1

It's mostly important to strip the whitespaces if you use sys.stdin.readline (which contains a trailing newline character) and you don't know if the function that uses that value can handle additional whitespaces.


* Just FYI: The types float, complex, fractions.Fraction, and decimal.Decimal also ignore leading and trailing whitespaces so you don't need to strip the strings if you use any of those.

like image 104
MSeifert Avatar answered Nov 15 '22 05:11

MSeifert