Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between split() and replace(' ','')?

Suppose I want to create a list of the input

3 4 5 6 7

without the spacings. Is there a technical difference between list(map(int, input().split())) and list(map(int,input().replace(' ','')))?

I am inputting a list of this sort for a question on HackerRank. The split() version seems to always work, but the replace(' ','') version seems to only work for short length inputs.

like image 890
Rishi Avatar asked Jul 20 '26 19:07

Rishi


1 Answers

list(map(int,input().replace(' ',''))) will fail if your numbers have more than two digits since it converts each character to an int.

Example:

>>> inp = '1 2 3 50'

>>> list(map(int, inp.replace(' ','')))
[1, 2, 3, 5, 0]

>>> list(map(int, inp.split()))
[1, 2, 3, 50]

For the same reason, it also isn't able to handle negative values or floats.

like image 84
Loocid Avatar answered Jul 23 '26 08:07

Loocid