1

I'm having trouble with creating a function that takes an argument of a string and returns just the numbers in type str. My code looks something like this.:

def check_if_number(number_string):
    for ch in number_string:
        if ch.isdigit():
            num = number_string[ch]
            return num
print(check_if_number('1655t'), end='')

It should print: 1655

MSeifert
  • 145,886
  • 38
  • 333
  • 352
KBdoesCode
  • 39
  • 1
  • 6
  • What is `check_leap_year` function ? Also, what exact error you are getting ? – Jarvis Feb 08 '17 at 02:41
  • it's check_if_number. Sorry for the confusion. I'm getting TypeError: string indices must be integers. When I run the code – KBdoesCode Feb 08 '17 at 02:42
  • Don't return inside the for loop, return at the end. You also need a result variable to add to as `num` is just a single character, `ch` is still a string you you need to convert that to an `int` after checking, as you can't index with it. Are you trying to remove all non-digit characters or just check if the digit isn't only digits? – Steven Summers Feb 08 '17 at 02:42
  • 1
    can you please show me what you mean with the code. – KBdoesCode Feb 08 '17 at 02:46
  • There is so much contradictory stuff going on here, it would be really nice if you explained what you expect each individual statement to do so we can really help you figure this out instead of just spewing Python knowledge. – Mad Physicist Feb 08 '17 at 03:04

5 Answers5

1

You should add each char to a string if it is a digit :

def check_if_number(number_string):
    digit_string = ""
    for ch in number_string:
        if ch.isdigit():
            digit_string += ch
    return digit_string
print(check_if_number('1655t'))

# 1655

Note that you can also use the re library :

import re
re.sub("\D", "", "1655t")

#1655

This code replace every non-digit character (matched by \D) by an empty string.

Have a look at this question to find more way to do it

Community
  • 1
  • 1
Fabich
  • 2,768
  • 3
  • 30
  • 44
  • I see the two things I was doing wrong. Not having a result variable like digit_string to add to and placing the return outside of the loop. This opens my eyes. – KBdoesCode Feb 08 '17 at 04:37
  • @KBdoesCode Great ! If this solves your problem and answer your question you can accept the answer (the tick symbol on the left of the question). – Fabich Feb 08 '17 at 12:59
0

You can do this :

def check_if_number(number_string):
    num = ""
    for ix in number_string :
        if ix.isdigit():
            num += ix
    return int(num)

This function will return 1655, if the input is 1655t. You return from the function once you scan the complete string and append all ints to a string.

Jarvis
  • 8,494
  • 3
  • 27
  • 58
0

Assuming all numbers are together (i.e. No letters exist between digits like "1e234g7"),

def check_if_number(number_string):
    num = ''
    for ch in number_string:
        if ch.isdigit():
            num += ch
    return num

print(check_if_number('1655t'), end='')

This will return a string that only has digits in it. If you want to return a type int, then simply do return int(num).

If you want to take floats into account as well:

def check_if_number(number_string):
    num = ''
    for ch in number_string:
        if ch == '.' or ch.isdigit():
            num += ch
    return num

print(check_if_number('1655t'), end='')

Similarly, this will return a string. If you want type float, simply do return float(num).

I tried not to deviate too much from what you already had... I hope this helps.

spicypumpkin
  • 1,209
  • 2
  • 10
  • 21
  • @StevenSummers I didn't catch it at first lol I tried to make the edit as soon as possible but subways are hella slow today :/ – spicypumpkin Feb 08 '17 at 02:56
0

The easy way would be just using filter and concatenating the filtered letters in the end:

def check_if_number(number_string):
    return ''.join(filter(str.isdigit, number_string))
MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

I'm uncertain what check_leap_year() function is so I just commented it out and called the function you gave us instead.

When you pass anything into a function in order to manipulate it and spit it back out different than it came in you should create a new variable for the changed data set.

In this case I used num = ""

By initiating an empty string inside of the function I can now add the data that pass my condition to that new, empty string.

isdigit() returns a boolean. So instead of using if x.isdigit: get in the habit of checking the boolean. Try if x.isdigit() is True instead.

Return your finished new string AFTER it is finished. Make sure your return statement is indented correctly or you are only going to return one number instead of all of them. The return should be outside of the loop so that it will only return once the loop is done.

num_string = "1a2s3d4f5g666hhh777jjj888kkk9l0"
def check_if_number(number_string):
    num = ""
    for ch in number_string:
        if ch.isdigit() is True:
            num  += ch  
    return num

print(check_if_number(num_string))

Output:

>>> 1234566677788890
Riley Hughes
  • 1,344
  • 2
  • 12
  • 22
  • That's a well of knowledge. Thanks. So, what is the reasoning behind writing ch.isdigit() is True: if ch.isdigit() works the same for this loop? That part confused me a bit. I was told to not repeat my self when writing code. – KBdoesCode Feb 08 '17 at 04:45
  • Mostly just consistency and readability. You could also use `isdigit()` to determine if something is not a digit. In which case you would need to use the `is` operand. `if x.isdigit() is False:` A good rule of thumb is if you need it sometimes, but when you do not need it it gives you the same results, just make a habit of doing it. And if you ever have people reading your code in the future they will thank you – Riley Hughes Feb 08 '17 at 20:26