2011-04-13 139 views
3

我必須說這是因爲我是一個新手(學習),所以請放棄顯而易見的遺漏,尊重一個對你的世界有限的人(Python) 。使用ord()轉換字符串爲ascii

我的目標是從用戶獲取字符串並將其轉換爲十六進制和ASCII字符串。我用hex(encode("hex"))成功完成了這個任務,但是ascii沒有。我找到了ord()方法並嘗試使用該方法,如果我只使用:print ord(i),則循環遍歷並將值垂直打印到屏幕上,而不是我想要的那些值。所以,我試圖用一個字符串數組捕獲它們,這樣我就可以將它們連接到一行字符串,並在'Hex'值下水平打印它們。我已經用盡了我的資源來解決這個問題......任何幫助都是感激。謝謝!

while True: 
    stringName = raw_input("Convert string to hex & ascii(type stop to quit): ") 
    if stringName == 'stop': 
     break 
    else: 
     convertedVal = stringName.encode("hex") 
     new_list = [] 
     convertedVal.strip() #converts string into char 
     for i in convertedVal: 
     new_list = ord(i) 


     print "Hex value: " + convertedVal 
     print "Ascii value: " + new_list  
+1

你期待你的ASCII輸出看起來像什麼?逗號分隔的十進制值?即:「97,98,65,65」 – yan 2011-04-13 21:04:44

+0

如果用戶輸入字符串:'123431':hex = 313233343331 ascii = 49 50 51 52 51 49 – suffa 2011-04-13 23:31:07

+0

謝謝DP ....此外,我並不是故意最後一條評論的ascii值之間的空格。 – suffa 2011-04-13 23:38:36

回答

6

這是你在找什麼?

while True: 
    stringName = raw_input("Convert string to hex & ascii(type stop to quit): ").strip() 
    if stringName == 'stop': 
     break 

    print "Hex value: ", stringName.encode('hex') 
    print "ASCII value: ", ', '.join(str(ord(c)) for c in stringName) 
+0

是的!我的代碼與之前的代碼幾乎完全相同,但切換了!爲什麼在stringName ...行上使用.strip()?再次,謝謝! – suffa 2011-04-13 23:45:07

3

像這樣的事情?

def convert_to_ascii(text): 
    return " ".join(str(ord(char)) for char in text) 

這給你

>>> convert_to_ascii("hello") 
'104 101 108 108 111' 
1
print "ASCII value: ", ", ".join(str(i) for i in new_list)