2

I'm trying to convert characters in string into ascii value in Python

Like ord('a[i]') but ord expects only character not string!!

Is there any other method to solve this problem in python .

Vilva
  • 811
  • 12
  • 23

2 Answers2

9
>>> s = "string"
>>> map(ord, s)
[115, 116, 114, 105, 110, 103]
Sven Marnach
  • 530,615
  • 113
  • 910
  • 808
3

An alternative to Sven's answer:

[ord(c) for c in s]

... or the corresponding generator expression:

(ord(c) for c in s)
Fred Larson
  • 58,972
  • 15
  • 110
  • 164
  • 1
    +1 I prefer to use list comprehensions to `map` where possible – Alasdair Nov 04 '11 at 15:15
  • @Alasdair when would it ever *not* be possible? – Karl Knechtel Nov 04 '11 at 15:25
  • 1
    @Alasdair Comprehension is great if you'd have to create lambda (or normal function) and/or use `filter` as addition to the `map`. But when you are just calling existing function (for example `int`) it's (in my opinion) more cleaner and readable to use map. And according to my simple measurement I just did it's faster. – rplnt Nov 04 '11 at 15:36