如何使函数返回给定字符串中每个字符的ascii值

时间:2019-04-26 06:35:29

标签: python-3.x

需要创建一个接收字符串并以(103、104、105等)形式返回字符串中每个字母的ascii值的函数

3 个答案:

答案 0 :(得分:0)

如果您无法获取ASCII值:您需要的是ord函数https://docs.python.org/3/library/functions.html#ord

这实际上为您提供了Unicode代码点-但这等效于ASCII范围(最大为0xFF iirc)

答案 1 :(得分:0)

为此使用ord函数

In [12]: ord('g')                                                               
Out[12]: 103

In [13]: ord('h')                                                               
Out[13]: 104

In [14]: ord('i')                                                               
Out[14]: 105

作为附加花絮,使用chr函数将ascii值转换为字母

In [15]: chr(103)                                                               
Out[15]: 'g'

In [16]: chr(104)                                                               
Out[16]: 'h'

In [17]: chr(105)                                                               
Out[17]: 'i'

您可以猜到。

In [18]: chr(ord('g')) == 'g'                                                   
Out[18]: True

要获取字符串所有字符的ascii值,只需对所有字符运行一个for循环

s = 'helloworld'

for c in s:
    print(ord(c))                                                                      
104
101
108
108
111
119
111
114
108
100

答案 2 :(得分:0)

可以在python中使用winMain=new electron.BrowserWindow({ "width":960, "height":600, "minWidth":800, "minHeight":500, "backgroundColor":"#FFF", "center":false, "icon":__dirname+"/static/logo.png", "webPreferences":{ "preload":path.join(__dirname,"preload.js"), "defaultFontFamily":{ "monospace":"Consolas" // or "Noto Sans" or "'Noto Sans'" or "Courier New" or "'Courier New'" }, "defaultEncoding":"UTF-8" } }); // winMain.loadFile("index.html"); winMain.loadURL(url.format({ "protocol":"file", "slashes":true, "pathname":path.join(__dirname,"index.html") })); 函数。

单行解决方案:

ord()

使用string = "ThisIsString!" [ord(c)] for c in string] 循环

for
  

[84,104,105,115,73,115,83,116,114,105,110,103,33]