Andrew Tam
Andrew Tam

Reputation: 1

How do I check if a character in a string is a non-letter?

So the code I'm writing is intended to replace all the vowels with alternate letters, and then return "Error" if any character in a particular string is a non letter. I got the first part to work but how do I check for a non letter?

def signature(name):
    names = name
    for n in name:
        if n == "a":
             names = names.replace(n,'b')
        if n == 'e':
             names = names.replace(n, 'f')
        if n == 'i':
             names = names.replace(n,'j')
        if n == 'o':
             names = names.replace(n, 'p')
        if n == 'u':
             names = names.replace(n,'v')

    return names

Upvotes: 0

Views: 1324

Answers (1)

Owen
Owen

Reputation: 919

As Paul suggests, use isalpha to check if a string contains only letters:

assert name.isalpha()

Using assert in this way will raise an error if the name contains a non alphabet character.

Your vowel conversion can be simplified:

def replace(c):
    if c in 'aeoui':
        return chr(ord(c) + 1)
    return c # return c if not a vowel

name = "".join([replace(c) for c in name])
  • Use ord to convert the character to an integer
  • Increment this by one
  • Use chr to build a character back from the integer

Upvotes: 3

Related Questions