How to remove a word that begins with punctuation

While I have a method of removing punctuation from a sentence, I want to remove a word that begins with punctuation from the sentence as well. Example:

¿Que es senor numbre?

process

es senor numbre?

or

How !important is it?

process

How is it?

Any tips would be wonderful.

Posted Dec 8, 2021, 6:20 PM UTC

311
-Rock-Obvious-•

punctuation = ['?', '!']

words = string.split()
for word in words:
    if word[0] in punctuation:
        #Do stuff
3
sinithwOP•

Wouldn't this also remove words with ending punctuation?

1
-Rock-Obvious-•

word[0] means to check the 0th character of string. -1th index is the last character.
https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3

4
sinithwOP•

Ah! I see. Thank you. I think I will use string.punctuation though for my comparison, I didn't even think about just checking the first element of the string. Again, thank you.

1
sarrysystfrom solutions import *•

Beware that ¿ is not included in string.punctuation.

6

Don't want to create a thread.

I want to write

A + b + c + d

Using a loop, but how do stop it from being

A+b+c+d+

I saw somewhere that using at the end of loop

Return str[:-1] worked

But how?

1
-Rock-Obvious-•

Search for slicing of strings in python. [:-1] says give me string from 0 index to -2th index. Endpoint is not included.

A better way is to use str.join method it wont add an extra "plus"

1

I get that the endpoint is not included, but my question is that it was a loop, so wouldn't that lead to the end point i.e. '+' not being included in each loop?

Since a+ is first loop B+ next loop and D+ last loop

Leading to A b c d

1
-Rock-Obvious-•

Can you send the code?

1
__coder__•

You can use the startswith() method to check if a string starts with a substring, and then use the join() method to join together the words that meet your criteria.

punctuation = ('¿', '?', '¡', '!')
original = "¿Que es senor numbre?"
new = " ".join((
    word for word in original.split() 
    if not word.startswith(punctuation)
))

The " " in " ".join means to separate each word in the new string with a space.

1