简体   繁体   English

如何在 python 的 ascii 中打印 32 个控制字符?

[英]How to print 32 control characters in ascii in python?

ASCII characters are from 0 to 127 but only some numbers are printable characters. ASCII 字符是从 0 到 127,但只有一些数字是可打印字符。 32 of them are control characters and are not printable.其中 32 个是控制字符,不可打印。 Is there any way to assign any character to that hex values of 32 character?有没有办法将任何字符分配给 32 个字符的十六进制值? so that i can print all the 127 characters.这样我就可以打印所有 127 个字符。 I don't want UTF since it take 2 bytes per some characters.我不想要 UTF,因为每个字符需要 2 个字节。 I want all characters from 0 to 255 for one byte per character.我想要从 0 到 255 的所有字符,每个字符一个字节。 I'm planning to save the file in ANSI format.我打算将文件保存为 ANSI 格式。

By the way I'm developing this program in Python.顺便说一句,我正在 Python 中开发这个程序。

Kindly advice.好心劝告。

Code代码

Text文本

It is possible.有可能的。 Each text file is also a binary file.每个文本文件也是一个二进制文件。 Therefore all characters, whether they printable or not, are represented by a number [0..255].因此,所有字符,无论它们是否可打印,都由一个数字 [0..255] 表示。 If you read the file char by char, you can always retrieve that number with ord(char) .如果您按字符读取文件,则始终可以使用ord(char)检索该数字。

Instead of a standard UTF-8 text interpretation (Python uses UTF-8 as internal representation), you can use your own private MYASCII table that translates the ordinal number to the character you want.代替标准的 UTF-8 文本解释(Python 使用 UTF-8 作为内部表示),您可以使用自己的私有MYASCII表将序数转换为想要的字符。

Writing to file is similar: Suppose you have a 'strange' character 'я' , you can write the ordinal value of its place in your own MYASCII table then instead of writing that character, you write the ordinal number to file with chr(num) .写入文件类似:假设您有一个“奇怪”字符'я' ,您可以将其位置的序数值写入您自己的MYASCII表中,然后不用写入该字符,而是将序数写入文件chr(num) .

This way you define your own 'encodings'.这样您就可以定义自己的“编码”。 That is, how you would interpret the numbers [0.. 255] in the text file.也就是说,您将如何解释文本文件中的数字 [0.. 255]。 However, you always need your own MYASCII table to interpret the file.但是,您总是需要自己的 MYASCII 表来解释文件。 For any program without that table, that is for example any external text editor, it will be displayed as if it where ANSI.对于没有该表的任何程序,例如任何外部文本编辑器,它将被显示为 ANSI 所在的位置。

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

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