So, as an example, let’s say that there is only one line of code in the program, and that line of code is n = input(), and let’s say that the user inputted random123. How can I make it so when I print n, it only prints the integers of n, or 123? Note that I want this to work even if the user input is random123random456. If the user input IS “random123random456,” I want it to print 123456.
            Asked
            
        
        
            Active
            
        
            Viewed 66 times
        
    1
            
            
         
    
    
        thatonehayk
        
- 67
- 5
3 Answers
4
            
            
        You can use a generator expression with a call to the str.isdigit method as a filter:
''.join(c for c in n if c.isdigit())
 
    
    
        blhsing
        
- 91,368
- 6
- 71
- 106
1
            
            
        Another quick way is to remove any non numeric character from the string with regular expressions
Example:
import re
test = "123string456"
result = re.sub('\D', '', test)
Here \D means any character different from 0...9 You can then replace it with empty character
Some results:
>>> import re
>>> re.sub('\D', '', 'random123random456')
'123456'
>>> re.sub('\D', '', 'random123')
'123'
Best regards
 
    
    
        manuel_b
        
- 1,646
- 3
- 20
- 29
0
            
            
        test = "123string456"
output = str()
for each in test:
    try:
        n = int(each)
        output = "{}{}".format(output,n)
    except:
        pass
print(output)
 
    
    
        ap288
        
- 41
- 5
- 
                    1I would strongly recommend replacing `except:` with `except ValueError:`. See [What is wrong with using a bare 'except'?](https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except). – Xukrao Mar 11 '19 at 01:06