简体   繁体   English

使用标点符号列表制作 re.sub

[英]Making a re.sub using a list of punctuation

Is there a way to take a list of punctuation, and put it into a re.sub.有没有办法获取标点符号列表,并将其放入 re.sub 中。 I was using f-string literals but the escape character breaks everything.我使用的是 f 字符串文字,但转义字符破坏了一切。 Should I just type it manually?我应该手动输入吗?

marks = [',', '。', '—', '《', '》', '□', '●', '/', '{', '}', '·', '、', '「', '」','|']
punctuation = '|'.join(['\\' + f'{n}' for n in marks])
re.sub('\ |\?|\.|\!|\/|\;|\:', '', 'line')

Nothing wrong with what you're doing, though I prefer to use a character class. Can't be 100% sure from your post but it sounds like you're trying to remove certain punctuation from a string?尽管我更喜欢使用字符 class,但您所做的没有任何问题。不能 100% 确定您的帖子,但听起来您正试图从字符串中删除某些标点符号? Example:例子:

marks = [',', '。', '—', '《', '》', '□', '●', '/', '{', '}', '·', '、', '「', '」','|']
punctuation = '[' + ''.join(['\\' + f'{n}' for n in marks]) + ']'

x = re.sub(punctuation, '', 'li..n?e-asdfa「sdf??ag\/as●dga,s|g`da')

print(punctuation)
print(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM