-1

Need to make a function that takes in a string and returns the ascii values for each letter in the string in a form of (103, 104, 105, etc.)

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
clurb
  • 11
  • 1

3 Answers3

0

If you just can't get the ASCII values: what you want is the ord function https://docs.python.org/3/library/functions.html#ord

This actually gives you the unicode code Point - but that's equivalent in the ASCII range (which is up to 0xFF iirc)

SV-97
  • 431
  • 3
  • 15
  • I tried using the ord function but since it can only take in one character at a time it stumped me since the test code runs it with a string longer that one character – clurb Apr 26 '19 at 06:42
  • Ah well you need to iterate over your string so that you get each character. See for example here: https://stackoverflow.com/questions/538346/iterating-each-character-in-a-string-using-python – SV-97 Apr 26 '19 at 06:45
0

Use the ord function for that

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

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

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

As an extra tidbit, use the chr function to convert the ascii value to letter

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

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

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

And as you can guess.

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

To get ascii values for all characters of a string, just run a for loop over all characters

s = 'helloworld'

for c in s:
    print(ord(c))                                                                      
104
101
108
108
111
119
111
114
108
100
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

It can be done using the ord() function in python.

One line solution:

string = "ThisIsString!"
[ord(c)] for c in string]

Using for loop

asciis = []

for c in string:
    asciis.append(ord(c))

print(asciis)

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

betelgeuse
  • 1,136
  • 3
  • 13
  • 25