过滤list中只含有标点符号的字符串元素
时间: 2023-04-07 12:03:03 浏览: 52
可以使用正则表达式来过滤只含有标点符号的字符串元素,具体实现可以参考以下代码:
import re
def filter_punctuation_only(lst):
pattern = r'^[\W]+$' # 匹配只含有标点符号的字符串
return [s for s in lst if re.match(pattern, s)]
# 示例
lst = ['hello', 'world!', '...', 'goodbye', '!', '']
filtered_lst = filter_punctuation_only(lst)
print(filtered_lst) # ['...', '!', '']
相关问题
过滤list中只含有标点符号的字符串
可以使用正则表达式来过滤list中只含有标点符号的字符串,具体代码如下:
import re
lst = ["Hello, world!", "How are you?", "!!!", "12345", ""]
punctuation_pattern = re.compile(r'^[\W_]+$')
filtered_lst = [s for s in lst if punctuation_pattern.match(s)]
print(filtered_lst)
输出结果为:['!!!']
这个代码会将lst中只含有标点符号的字符串过滤出来,即['!!!']。
去除掉list中只含有标点符号的字符串元素
可以使用Python的正则表达式来去除只含有标点符号的字符串元素,代码如下:
import re
my_list = ["hello", ",", "world", ".", "!", " ", "goodbye", "(", ")", "?"]
new_list = [x for x in my_list if not re.fullmatch(r'[^\w\s]+', x)]
print(new_list)
输出结果为:['hello', 'world', ' ', 'goodbye']