-1

How to check special symbols such as !?,(). in the words ending? For example Hello??? or Hello,, or Hello! returns True but H!??llo or Hel,lo returns False.

I know how to check the only last symbol of string but how to check if two or more last characters are symbols?

AlTs
  • 301
  • 3
  • 9

5 Answers5

3

You may have to use regex for this.

import re

def checkword(word):
    m = re.match("\w+[!?,().]+$", word)
    if m is not None:
        return True
    return False

That regex is:

\w+          # one or more word characters (a-zA-z)
[!?,().]+    # one or more of the characters inside the brackets
             #   (this is called a character class)
$            # assert end of string

Using re.match forces the match to begin at the beginning of the string, or else we'd have to use ^ before the regular expression.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
1

You can try something like this:

word = "Hello!"

def checkSym(word):
    return word[-1] in "!?,()."

print(checkSym(word))

The result is:

True

Try giving different strings as input and check the results.

In case you want to find every symbol from the end of the string, you can use:

def symbolCount(word):

    i = len(word)-1
    c = 0
    while word[i] in "!?,().":
        c = c + 1
        i = i - 1

    return c

Testing it with word = "Hello!?.":

print(symbolCount(word))

The result is:

3
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
0

You could try this.

string="gffrwr."
print(string[-1] in "!?,().")
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
0

If you want to get a count of the 'special' characters at the end of a given string.

special = '!?,().'
s = 'Hello???'

count = 0
for c in s[::-1]:
    if c in special:
        count += 1
    else:
        break

print("Found {} special characters at the end of the string.".format(count))
  • Could you explain what the `s[::-1]` syntax does? It seems fairly obvious, but I've never seen it before. – trent Oct 29 '17 at 22:22
  • It gets the list 's' and returns a shallow copy starting from the last element and ending at the first. Take a look here: https://stackoverflow.com/questions/3705670/best-way-to-create-a-reversed-list-in-python – Iosif Serafeimidis Oct 29 '17 at 22:25
0

You can use re.findall:

import re
s = "Hello???"
if re.findall('\W+$', s):
   pass
Ajax1234
  • 69,937
  • 8
  • 61
  • 102