2

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
4
  • raw_input already returns a string, so there you go, validation done. Unless you mean that the user shouldn't be allowed to type in 1234 (which would make the function return '1234'), in which case you'll need to be more specific about what you mean. Commented Mar 5, 2013 at 17:19
  • 1
    Everything that raw_input gives you is a string. Commented Mar 5, 2013 at 17:19
  • raw_input will only return strings. Commented Mar 5, 2013 at 17:20
  • I think by string you meant alphabets?? Commented Mar 5, 2013 at 17:20

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

5 Comments

"strings and not integers" as specified includes '/' and '^`{}'
Yeh sorry for the confusion thats what I meant this is part of an encryption program and of course it uses letters and of course encrypts them depending on the encryption method. But of course I don't want the user to be inputting numbers straight away. But thanks for that, it should work
If you're encrypting text, why can't that text include digits? You're saying that you'll encrypt 'foo' but not '123'? What about 'foo123'?
But when would you encrypt a message saying that?
You don't want to encrypt dates, times, or addresses?
0

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."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.