user1655562
user1655562

Reputation: 81

General Python Programming 2.7 data validation

I was wondering what functions should I use for this def function so that the user can only enter strings and not integers -

def GetTextFromUser():

    TextFromUser = raw_input('Please enter the text to use: ')

    return TextFromUser

Upvotes: 2

Views: 142

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251136

raw_input() always returns a string. But ,if by string you meant only alphabets are allowed, then you can use: str.isalpha()

S.isalpha() -> bool

Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.

examples:

In [9]: 'foo'.isalpha()
Out[9]: True

In [10]: 'foo23'.isalpha()
Out[10]: False

Upvotes: 6

Hut8
Hut8

Reputation: 6342

According to the documentation, raw_input always returns a string. If you never want it to return an integer, I would try to convert it to an integer using int() and catch an exception if it fails. If it doesn't fail, immediately after, return the value. This follows the Pythonic style of "it's better to ask for forgiveness than for permission."

Upvotes: 0

Related Questions