mwstray
mwstray

Reputation: 355

Making sure no integers in a string?

I have a simple question. I'm just wanting to know how I would have my program read the "input()" and see if there are integers or any kind of number in the string, and if so then print out a message saying so. Pretty much I just want to know how I would make sure that no one enters in a number for their name. Thanks!

yn = None
while yn != "y":
    print("What is your name?")
    name = input()
    print("Oh, so your name is {0}? Cool!".format(name))
    print("Now how old are you?")
    age = input()
    print("So your name is {0} and you're {1} years old?".format(name, age))
    print("y/n?")
    yn = input()
    if yn == "y":
        break
    if yn == "n":
        print("Then here, try again!")
print("Cool!")

Upvotes: 3

Views: 362

Answers (3)

mgilson
mgilson

Reputation: 309889

Depending on the strings, regular expressions might actually be faster:

import re

s1 = "This is me"
s2 = "this is me 2"
s3 = "3 this is me"

regex = re.compile(r'\d')
import timeit
def has_int_any(s):
    return any(x.isdigit() for x in s)

def has_int_regex(s,regex=re.compile(r'\d')):
    return regex.search(s)

print bool(has_int_any(s1)) == bool(has_int_regex(s1))
print bool(has_int_any(s2)) == bool(has_int_regex(s2))
print bool(has_int_any(s3)) == bool(has_int_regex(s3))


for x in ('s1','s2','s3'):
    print x,"any",timeit.timeit('has_int_any(%s)'%x,'from __main__ import has_int_any,%s'%x)
    print x,"regex",timeit.timeit('has_int_regex(%s)'%x,'from __main__ import has_int_regex,%s'%x)

My results are:

True
True
True
s1 any 1.98735809326
s1 regex 0.603290081024
s2 any 2.30554199219
s2 regex 0.774269104004
s3 any 0.958808898926
s3 regex 0.656207084656

(Note that the regular expression engine wins even in the case specifically designed for any to be fastest). however, with longer strings, I'm willing to bet that any will eventually be faster.

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121714

Use the str.isdigit() method on strings, together with the any() function:

if any(c.isdigit() for c in name):
    # there is a digit in the name

.isdigit() returns True for any string that consists only of digits. This includes any Unicode character that is marked as a numeric digit or numeric decimal.

any() loops over the sequence you pass in and returns True as soon as it finds the first element that is True, and False if all elements are False.

Demo:

>>> any(c.isdigit() for c in 'Martijn Pieters')
False
>>> any(c.isdigit() for c in 'The answer is 42')
True

Upvotes: 3

eumiro
eumiro

Reputation: 212845

see if there are integers or any kind of number in the string

any(c.isdigit() for c in name)

returns True for strings such as "123", "123.45", "abc123".

Upvotes: 3

Related Questions