简体   繁体   English

在 python 中打印转义序列字符

[英]Printing escape sequence character in python

I tried to print the escape sequence characters or the ASCII representation of numbers in Python in a for loop.我试图在for循环中打印 Python 中的转义序列字符或数字的 ASCII 表示。

Like:喜欢:

for i in range(100, 150):
    b = "\%d" %i
    print(b)

I expected the output like,我希望 output 喜欢,

A
B
C

Or something.或者其他的东西。

But I got like,但我觉得,

\100
\101

How to print ASCII representation of the numbers?如何打印数字的 ASCII 表示?

There's a builtin function for python called ord and chr有一个内置的 function 用于 python 称为ordchr

ord is used to get the value of ASCII letter, for example: ord用于获取 ASCII 字母的值,例如:

print(ord('h'))

The output of the above is 104上面的output是104

ord only support a one length string ord只支持一个长度的字符串

chr is inverse of ord chrord的倒数

print(chr(104))

The output of the above is 'h'上面的 output 是'h'

chr only supports integer. chr仅支持 integer。 float, string, and byte doesn't support浮点数、字符串和字节不支持

chr and ord are really important if you want to make a translation of a text file (encoded text file)如果要翻译文本文件(编码文本文件), chrord非常重要

You can use the ord() function to print the ASCII value of a character.您可以使用ord() function打印字符的 ASCII 值。

print(ord('b'))

> 98

Likewise, you can use the chr() function to print the ASCII character represented by a number.同样,您可以使用chr() function打印由数字表示的 ASCII 字符。

print(chr(98))

> b

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

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