简体   繁体   English

如何删除字符串后面的所有标点符号?

[英]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.

相关问题 如何从熊猫系列中的字符串中删除标点符号 - How do I remove punctuation from a string in a pandas Series 如何在Python中用“”替换字符串中的所有标点符号? - How do I replace all punctuation in my string with “” in Python? 从字符串中删除所有标点符号 - Remove all punctuation from string 如何在Python中替换字符串中的标点符号? - How do I replace punctuation in a string in Python? 如何删除标点符号并使python的多个字符串语句的所有评论小写 - How can i remove punctuation and make all the reviews lower case for multiple string statements for python 如何从字符串中删除标点符号? (蟒蛇) - How Do You Remove Punctuation From A String? (Python) 如何从 python 数组的导入列表中删除标点符号 - How do i remove Punctuation from import list for a python array 如何匹配 pandas 列中的字符串,然后返回它后面的内容? - How do I match a string in a pandas column then return what follows it? 如何精确匹配字符串中的所有单词,包括以 ',?.?'"' 结尾的单词,但不使用正则表达式匹配任何其他标点符号? - How do I exact match all the words in a string includes those ends with '!,?.'"' but do not match those with any other punctuation using regex? 如何使用列表理解删除字符串中的标点符号? - How To Remove Punctuation In String Using List Comprehension?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM