Home > Mobile >  How to check if string contains only english characters, exclamation marks in the end?
How to check if string contains only english characters, exclamation marks in the end?

Time:10-31

For example "hello!!" should return true, whereas "45!!","!!ok" should return false. The only case where it should return true is when string has English characters (a-z) with 0 or more exclamation marks in the end.

Following is my solution using iterative method, however I want to know some clean method having fewer lines of code (maybe by using some python library).

def fun(str):
    i=-1
    for i in range(0,len(str)):
        if str[i]=='!':
            break
        elif (str[i]>='a' and str[i]<='z'):
            continue
        else:
            return 0

    while i<len(str):
        if(str[i]!='!'):
            return 0
        i =1

    return 1

print(fun("hello!!"))

CodePudding user response:

Regex can help you out here. The regular expression you're looking for here is:

^[a-z] !*$

This will allow one or more English letters (lowered case, you can add upper case as well if you'll go with ^[a-zA-Z] !*$, or any other letters you'd like to add inside the square brackets) and zero or more exclamation marks at the end of the word.

Wrapping it up with python code:

import re
pattern = re.compile(r'^[a-z ] !*$')
word = pattern.search("hello!!")
print(f"Found word: {word.group()}")
  • Related