[Tutor] string codes

ALAN GAULD alan.gauld at btinternet.com
Tue Nov 26 15:59:54 CET 2013


Pleae use ReplyAll to include the list.


> c = ord(s[2])
>
>Yes, that's it: i forgot about Python's builtin functions, only searched among 
>methods. Then, two more questions:
>-1- Why isn't this a str method? s.ord() [or better s.code()] looks natural, 
>doesn't it?Because it operates on a single character not a whole string.
And ordinal is the correct name for the numerical position of the character, 
code is a woolly term that could mean just about anything.

-2- Apparently, I need to create a 1-char-long substring just to get the ordinal 
>
>code? Isn't that unneeded runtime work? Or does the compiler translate this to 
>only getting the i-th code, without creating any substring? 
>
>You seem to have a hangup about creating substrings?  A one char substring 
it just a single byte, that's not a big deal. In the bigger scheme of things its not 
going to produce any noticeable performance overhead.
Else, what about extending the ord func with an index param:
>    ord(s, index=0)How would moving the indexing inside ord be an improvement? It's still doing 
exactly the same job.

or better:
>
>    s.code(index=0)How would that look in a loop:

for c in mystring:
     print ord(c)

for index in range(len(mystring)):
    print mystring.code(index)

I know which I prefer


Aren't you as surprised as I am, that this param does not exist?
>No, I'd be amazed if it did.

> test = s.startswith("bcd", 1, -1)
>
>All right! Then, isn't startswith a misnomer?
>No because its testing if the substring startswith your search string.
In your example the substring is 'bcde' and it starts with 'bcd'.

If you want to trest equality of a substring you need to ensure the 
substring and search string are equal in length.
[You are right, Alan, but I wouldn't have found there better than in the ref 
>manuals: True but help() is faster! :-)

help(str) at the command line does not list ord() as a string-related 
>True, because it's char based so a builtin like len()

Alan g.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131126/77470f7a/attachment-0001.html>


More information about the Tutor mailing list