[Tutor] string codes

Danny Yoo dyoo at hashcollision.org
Tue Nov 26 21:01:10 CET 2013


Hi Denis,

For reference, you can explore the documentation to find out what strings
can do:

    http://docs.python.org/3/library/stdtypes.html#text-sequence-type-str



> What is the method to get a code or list of codes inside a string:
>         s = "abcde"
>         c = s.code(2)
>         assert(c == 0x63)
> ?

Strings are sequences, so we can iterate over them to get the individual
code points, using the ord() function:

    http://docs.python.org/3/library/functions.html#ord

For example:

#################
>>> map(ord, "abcde")
[97, 98, 99, 100, 101]
#################


If you prefer list comprehensions, its use is similar:

#############################################
>>> [ord(ch) for ch in "hello world"]
[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
#############################################




> Is there a method to compare a substring, without building a substring
from the big one? Like startswith or endswith, but anywhere inside the
string?
>         test = s[1, -1] == "bcd"        # no!, builds a substring
>         test = s.sub_is(1, -1, "bcd")   # yes! what I'm searching
>


According to:

    http://docs.python.org/3/library/stdtypes.html#str.find

you can optionally pass in "start" and "end" keyword arguments to apply
boundaries on the string you're searching.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131126/444e0d8f/attachment.html>


More information about the Tutor mailing list