python challenge question (string manipulation)

Caleb Hattingh caleb.hattingh at gmail.com
Wed Mar 29 15:24:20 EST 2006


John

In python, strings are immutable - you have to create a new string no
matter what you do.

Also, I suspect you meant to say:

>>> alphabet = string.ascii_lowercase
>>> code = alphabet[2:] + alphabet[:2]

I had a similar need recently for a guitar chord generator program I've
been working on.  Here is a "shift" function from my utilities module:

def shift(list,num):
    '''Shifts sequence "list" by "num" places.
    if num is positive, list scrolls forwards,
    otherwise, backwards.'''
    if abs(num) > len(list):
        num=num%len(list) # Use mod to remove full list entry rotations
    newlist=list[-num:]+list[:-num]
    return newlist

I actually create a new list here, although since lists are mutable, I
could probably just change items in-place.   There is very likely
something already in the builtins or the standard library for this, but
I just haven't searched hard enough.

Interesting trap I kept falling into: calling a guitar string a
"string" and then having collisions with the python type of the same
name.   Over and over again :)

Regards
Caleb




More information about the Python-list mailing list