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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With