Python 字符串文字中的特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28056843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Special Characters in string literals
提问by Illyduss
I am making a set in Python to house all the symbols on my keyboard, but obviously a few pose some issues. Is there a way to get them all in there without encountering problems?
我正在用 Python 制作一个集合来容纳我键盘上的所有符号,但显然有一些会带来一些问题。有没有办法让他们都在那里而不会遇到问题?
Here is my set:
这是我的套餐:
symbols = {`,~,!,@,#,$,%,^,&,*,(,),_,-,+,=,{,[,},},|,\,:,;,",',<,,,>,.,?,/}
To get around commenting out most of it, since in Python #
is to comment, I enclosed everything like so:
为了避免注释掉大部分内容,因为在 Python 中#
是注释,所以我将所有内容都包含在内:
symbols = {'`','~','!','@','#','$','%','^','&','*','(',')','_','-','+','=','{','[','}','}','|','\',':',';','"',''','<',',','>','.','?','/'}
Which works for that character, but now I can already see an issue when I come across the '
and \
. Is there a better way to make this set?
这适用于该角色,但现在当我遇到'
和时,我已经可以看到一个问题\
。有没有更好的方法来制作这个套装?
采纳答案by Illyduss
You can fix the backslash by escaping it and '
can be fixed by putting it in double quotes:
您可以通过转义反斜杠来修复它,并且'
可以通过将其放在双引号中来修复它:
symbols = {..., '\', ... "'", ...}
But typing all this out is pretty tedious. Why not just use string.punctuation
instead:
但是把所有这些都打出来是很乏味的。为什么不直接使用string.punctuation
:
>>> from string import punctuation
>>> set(punctuation)
{'~', ':', "'", '+', '[', '\', '@', '^', '{', '%', '(', '-', '"', '*', '|', ',', '&', '<', '`', '}', '.', '_', '=', ']', '!', '>', ';', '?', '#', '$', ')', '/'}
>>>