[英]How do I remove all punctuation that follows a string?
It's for a game in which the user can input a value like "Iced tea.." I would like to manipulate the string to return "Iced tea" without the trailing punctuation marks. 这是一个用户可以输入像“冰茶”这样的值的游戏。我想操纵字符串返回“冰茶”而没有拖尾标点符号。
Looking for most elegant / simplest python solution. 寻找最优雅/最简单的python解决方案。
Tried 试着
def last_character(word):
if word.endswith('.' or ','):
word = word[:-1]
return word
which works if there's only one punctuation mark at the end. 如果最后只有一个标点符号,则有效。 But it's not all-encompassing. 但它并非包罗万象。
Found a Java solution : 找到了Java解决方案 :
String resultString = subjectString.replaceAll("([a-z]+)[?:!.,;]*", "$1");
>>> 'words!?.,;:'.rstrip('?:!.,;')
'words'
In this case, rstrip
is probably what you want. 在这种情况下, rstrip
可能就是你想要的。 But in general, it's not hard to translate something like that Java into Python. 但总的来说,将Java这样的东西翻译成Python并不难。 A direct translation would look like this: 直接翻译看起来像这样:
import re
subject_string = 'Iced tea..'
result_string = re.sub('([a-z]+)[?:!.,;]*',r'\1',subject_string)
import string
s='aaa...,'
count= 0
>>> for l in s[::-1]:
... if l in string.punctuation:
... count = count +1
... else:
... break
>>> s[:c]
'aaa'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.