-2

How do you check if a string has punctuation by using a loop. I was told to use the in operator

string = input("Enter a string")

for char in string:
    if char in "'.,;:?!":
        print("that string contains  punctuation")
        break 
    else:
        print("that string contains punctuation")
        break
  • @mindfolded `break` is necessary to short circuit the `for` loop once a punctuation character is found. – blhsing Oct 19 '18 at 15:29
  • Your solution is almost correct. The 1st break is important, but the second one is wrong. You should put the `else` clause below the `for` instead of the `if` – JBernardo Oct 19 '18 at 15:29

4 Answers4

1

Use string module's punctuation which handles all punctuations for you:

import string

if any(x in string.punctuation for x in s):
    print("that string contains punctuation")      
else: 
    print("that string contains no punctuation")

where s is your string.

Austin
  • 25,759
  • 4
  • 25
  • 48
1

You can use the for-else construct to print the message that the string does not contain punctuation if it finishes the loop without finding one:

string = input("Enter a string")

for char in string:
    if char in "'.,;:?!":
        print("that string contains punctuation")
        break 
else:
    print("that string does not contain punctuation")
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

That code is half right.

The if part is correct, because as soon as you find any punctuation, your goal is met and you don't need to keep looking, so you can correctly break out of the loop.

However the else part is wrong, because if the current character is not punctuation, you still have to keep looking -- the remainder of the string might have punctuation. Also the message is wrong; it should say the string doesn't have punctuation.

You can restructure the code to take advantage of the for/else construct:

string = input("Enter a string")

for char in string:
    if char in "'.,;:?!":
        print("that string contains punctuation")
        break
else:
    print("that string does not contain punctuation")

The else will execute if the loop makes it all the way to the end of the string without calling break.

John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

Or Check the other way round considering the string input would be longer than the punctuation string

string = input("Enter a string")

punch_string= "'.,;:?!"
for char in punch_string:
    if char in string:
        print("that string contains punctuation")
        break
else:
    print("that string does not contain punctuation")

A shorter version using set intersection

    if set(string).intersection(set("'.,;:?!" )):
        print("that string contains punctuation")
else:
    print("that string does not contain punctuation")
mad_
  • 8,121
  • 2
  • 25
  • 40