M.Sadek
M.Sadek

Reputation: 21

Convert a string to a list and convert the elements to integers

So I have a string and I want to convert it to a list

input:

"123|456|890|60"

output:

[123,456,890,60]

Another example, input:

"123"

output:

[123]

Here is what I did until now.

A=input()
n=len(A)
i=0
z=0
K=""
Y=[0]*n
while(i<n):
  if(A[i]=="|"):
    Y[z]=int(Y[z])
    j=+1
    K=""
  else:
    Y[z]=K+A[i]
  i+=1
print(Y)

Upvotes: 1

Views: 66

Answers (3)

Andrew Winterbotham
Andrew Winterbotham

Reputation: 1010

Here's a similar approach, using regular expressions instead:

import re

def convert_string(s):
    return map(int, re.findall(r'[0-9]+', s))    

Or using a list comprehension:

import re

def convert_string(s):
    return [int(num) for num in re.findall(r'[0-9]+', s)]

This is a more general approach and will work for any character (in this case '|') that separates the numbers in the input string.

Upvotes: 0

The6thSense
The6thSense

Reputation: 8335

Using list comprehension

Code:

[int(a) for a in "123|456|890|60".split("|")]

Output:

[123, 456, 890, 60]

Notes:

  • Split creates a list of strings here where the current strings are split at |
  • We are looping over the list and converting the strings into int

Upvotes: 0

timgeb
timgeb

Reputation: 78690

Thanks for editing in your attempt. Splitting a string and converting a string to an integer are very common tasks, and Python has built in tools to achieve them.

str.split splits a string into a list by a given delimiter. int can convert a string to an integer. You can use map to apply a function to all elements of a list.

>>> map(int, "123|456|890|60".split('|'))
[123, 456, 890, 60]

Upvotes: 4

Related Questions