Hi folks, ThompsonSensibl, so I'm new to Python.

This is probably a noob question...

I want to convert a String input to an Integer. I usually do it like this: number = int(someString). However this time this approach doesn't seem to be efficient at all.

So far I have:

``````#To get number inputs:
print 'Enter the numbers.'

#Getting the String input (...numbers of type String, not Integer!) into an array

#Converting String content of array into an Integer.
firstNumber = int(array)
secondNumber = int(array)
thirdNumber = int(array)
...#etc. etc.``````

As you can see, this conversion process (from String to Integer) is very inefficient as you must convert each cell one by one...

Is there a more efficient alternative solution to this conversion process???

Cheers,
ThompsonSensibl

You can write
[code=python]
int_array = [ int(s) for s in array ]
[/code]

[QUOTE=megaflo;1183309]Can't you just do this?
[code=python]
for a in array:
number = int(a)
[/code][/QUOTE]
Yes you can, but if you want to do something with the integers, you must store them somewhere.

## All 6 Replies

You can write

``int_array = [ int(s) for s in array ]``

Can't you just do this?

``````for a in array:
number = int(a)``````

Can't you just do this?

``````for a in array:
number = int(a)``````

Yes you can, but if you want to do something with the integers, you must store them somewhere.

Why? Without knowing the OP use case there may or may not be a reason to store the numbers.

Why? Without knowing the OP use case there may or may not be a reason to store the numbers.

No, Gribouillis's code is the most efficient.
There probably is a need to store the numbers, since his original code was something like

``````firstNumber = int(array)
secondNumber = int(array)
thirdNumber = int(array)``````

which is definitely storing the numbers.

You can easily do something within the loop iff you need to. Without knowing the use case, who can telll what the OP wants to do? Maybe you are correct, maybe me, but when it comes to computing, I don't like guessing!!!:)