Home > Mobile >  Python List Conversion to string and split
Python List Conversion to string and split

Time:01-27

Any Idea when I do the split on list( after converting to string) I am not getting the first and the last elements in the list....

if __name__ =="__main__":
    lst1= ['3 6 2 5'];
    lst1=str(lst1);
    a = [int(i) for i in lst1.split(' ') if i.isdigit()]
    print(a);

Outputs

[6, 2]

What I am looking for is

[2,3,5,6]

I think its due to the split characters which it finds after the 3(first element), but not sure how to resolve it.

CodePudding user response:

When you convert lst1 to a string, you get

"['3 6 2 5']"

When you split this, you get the list: fir

["['3", "6", "2", "5']"]

"['3".isdigit() and "5']".isdigit() are false, so it doesn't print those elements.

To get the result you expect, you should not convert the list to a string. You should index the list to get its elements.

for s in lst1:
    a = [int(i) for i in s.split(' ') if i.isdigit()]
    print(a)

CodePudding user response:

Try it.

lst1= ['3 6 2 5'];
a = [int(i) for i in lst1[0].split(' ') if i.isdigit()]
a.sort()
print(a)
  • Related