Ask coding questions

← Back to all posts
how to convert a string with numbers into an integer?
Egghead21 (6)

Line 44, Funcs.py is the problem
supposedly, it should remove the strings from the phrase to convert it into an integer.

Answered by AlexanderBirabe (101) [earned 5 cycles]
View Answer
Comments
hotnewtop
AlexanderBirabe (101)
myInt = ''
for i in list(myString):
  if i in '1234567890':
    myInt += i

myInt = int(myInt)
AlexanderBirabe (101)

If you think my post answered your question, mark it as the answer. @Egghead21

Egghead21 (6)

@AlexanderBirabe what is the myString thing do?
it isn't a list- so would it be myInt?

AlexanderBirabe (101)

myString is the string that contains a number you want to isolate. myInt is the extracted number.
@Egghead21

Egghead21 (6)

@AlexanderBirabe I'm confused- why would i wan't to isolate a number- do you mean the string part?

AlexanderBirabe (101)

Your question is 'how to convert a string with numbers into an integer?' The code I gave you takes a string with a number (myString) and outputs an integer (myInt).
For example, if myString was "I am 20 years old", myInt would end up being the number 20.
@Egghead21

Egghead21 (6)

@Egghead21 I put myInt instead of myString, and it worked!
Thanks

AlexanderBirabe (101)

Wait, are you just converting from a string straight to an integer?
If so, then just do myStr = int(myStr), which would convert the string myStr to it's integer form.
For example, if myStr was '10', then it would become the number 10.

@Egghead21