Python一些转义序列不起作用

时间:2015-11-06 19:03:26

标签: python unicode unicode-escapes

我测试了一些逃脱序列。他们中的大多数都有效,但有些则没有。这是为什么?

这是我为测试转义序列而编写的代码:

# -*- coding: UTF-8 -*-

tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split \non a line."
backslash_cat = "I'm \\ a \\ cat."

fat_cat = '''
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
'''

print tabby_cat
print persian_cat
print backslash_cat
print fat_cat

#while True:
#   for i in  ["/", "-", "|", "\\", "|"]:
#       print "%s\r" % i,

print "This should ring a bell \a"
print "Does this have a backspace\b"    
print "Printing \"double quotes\" and some \'single quotes\'"    
print "Formfeed.\fWill this work?"    
print "Linefeed.\nWill this work?"    
print "Print the character named name: \N{name}"    
print "Print a carriage return.\rWill this work?"    
print "A 16 bit unicode character: \u6C34"    
print "Let's check this vertical tab: \v\vWhat is this?"
print "This should output an octal value: \111"
print "This should output a hex value: \xAA"

终端输出:

    I'm tabbed in.
I'm split 
on a line.
I'm \ a \ cat.

I'll do a list:
    * Cat food
    * Fishies
    * Catnip
    * Grass

This should ring a bell 
Does this have a backspace
Printing "double quotes" and some 'single quotes'
Formfeed.
         Will this work?
Linefeed.
Will this work?
Print the character named name: \N{name}
Will this work?e return.
A 16 bit unicode character: \u6C34
Let's check this vertical tab: 

                               What is this?
This should output an octal value: I
This should output a hex value: �

不起作用的是:

  • 贝尔:\a
  • 退格:\b
  • 角色名称:\N{name}(已解决)
  • 16位和32位unicode字符:\u6C34(已解决)

如何使这些转义序列有效?

===== EDIT =====================

print u"Print the character named name: \N{BLACK SPADE SUIT}"
print u"A 16 bit unicode character: \u6C34"

Print the character named name: ♠
A 16 bit unicode character: 水
  • 16位和32位unicode字符:\u6C34
  • 角色名称:\N{name} 在使用u
  • 的字符串前面时,这些工作正常

1 个答案:

答案 0 :(得分:2)

\a\b序列工作正常,但您的终端可能会随意忽略它们。这些序列只是用于创建分别为十六进制值07和08的字节的别名:

>>> '\a'
'\x07'
>>> '\b'
'\x08'

两个序列分别产生一个字节。由接收终端将该字节解释为控制字符,终端可以自由地忽略该字节或做一些不同的字节。

有些终端会闪烁而不是响铃;这通常是可配置的。在我的终端\b上工作就好了移动光标;它不会删除前面的字符。当您在其后添加更多文本时,位置的变化将变为可见:

>>> print 'abc\b'
abc
>>> print 'abc\bd'
abd

d覆盖c字符,因为退格字符将光标位置移回一个位置。

Unicode转义序列仅在Unicode字符串中使用u'...'文字:

>>> print "A 16 bit unicode character: \u6C34"
A 16 bit unicode character: \u6C34
>>> print u"A 16 bit unicode character: \u6C34"
A 16 bit unicode character: 水
>>> print u"Print the character named: \N{CJK UNIFIED IDEOGRAPH-6C34}"
Print the character named: 水

请注意,如果它实际上支持打印的Unicode代码点,它还取决于您的终端(控制台)!