regarding list object's attributes

Viewed 166

While I am writing this code lst=list(map(int,input().split().strip())) then I am getting an AttributeError 'list' object has no attribute strip

But it is working when I remove the strip() method. My question is that list object also has no attribute split. So in this case (lst=list(map(int,input().split())) why it is not giving any error and why it is giving error in case of strip() method?

1 Answers

Before you read the rest of the answer: you shouldn't have to strip() after you call split() because split() will consider multiple whitespace characters as a single delimiter and automatically remove the extra whitespace. For example, this snippet evaluates to True:

s1 = "1 2 3"
s2 = "1       2       3"
s3 = "   1   2   3   "

s1.split() == s2.split() == s3.split()

split() and strip() are both attributes of string objects!

When you're confused by code that's been stuffed into one line, it often helps to unravel that code out over multiple lines to understand what it's doing

Your line of code can be unraveled like so:

user_input_str = input()

split_input_list = user_input_str.split()

stripped_input = split_input_list.strip() ### ERROR!!!

lst = list(map(int, stripped_input))

Clearly, you tried to access the strip() method of a list object, and you know that doesn't exist.

In your second example, you do

user_input_str = input()

split_input_list = user_input_str.split()

lst = list(map(int, split_input_list))

Which works perfectly fine because you don't try to access strip() on a list object

Now to fix this, you need to change the order of operations: first, you get your input. Next, strip it. This gives you back a string. Then, split this stripped string.

user_input_str = input()

stripped_input_str = user_input_str.strip() ### No error now!

split_input_list = stripped_input_str.split()

lst = list(map(int, split_input_list))

#or in one line:
lst = list(map(int, input().strip().split()))

Or, if you want to strip each element of the split input list, you will need to map the strip() function to split_input_list like so:

user_input_str = input()
split_input_list = user_input_str.split()

stripped_input_list = list(map(str.strip, split_input_list))

lst = list(map(int, stripped_input_list))

#or in one line
lst = list(map(int, map(str.strip, input().split())))

# or, create a function that calls strip and then converts to int, and map to it
def stripint(value):
    return int(value.strip())

lst = list(map(stripint, input().split()))
Related