2016-02-11 40 views

回答

1
>>> text = "[email protected]#$%^&*()" 
>>> from string import punctuation 
>>> for p in punctuation: 
...  if p in text: 
...    print p 
... 

它会打印所有来自文本的标点字符。

! 
# 
$ 
% 
& 
(
) 
* 
@ 
^ 

OR

>>> text = "[email protected]#$%^&*()" 
>>> [char for char in punctuation if char in text] 
['!', '#', '$', '%', '&', '(', ')', '*', '@', '^'] 
0

我不知道如何与re模块做到这一点,但您可以使用列表理解:

from string import punctuation 
old_string = "This, by the way, has some punctuation!" 
new_string = "".join(char for char in old_string if char in punctuation) 
print(new_string) 
#,,! 
相关问题