next alpha sequence value from var pointing to array
Peter Otten
__peter__ at web.de
Thu Jun 7 08:59:40 EDT 2012
jdmorgan wrote:
> Hello,
Welcome!
> I am still fairly new to python, but find it to be a great scripting
> language.Here is my issue:
>
> I am attempting to utilize a function to receive any sequence of letter
> characters and return to me the next value in alphabetic order e.g. send
> in "abc" get back "abd".I found a function on StackExchange (Rosenfield,
> A 1995) that seems to work well enough (I think):
Please don't try to be clever about formatting your mail. Use text only.
> /def next(s):/
>
> /strip_zs = s.rstrip('z')/
>
> /if strip_zs:/
>
> /return strip_zs[:-1] + chr(ord(strip_zs[-1]) + 1) + 'a' * (len(s) -
> len(strip_zs))/
>
> /else:/
>
> /return 'a' * (len(s) + 1)/
This should be
def next_alpha(s):
strip_zs = s.rstrip('z')
if strip_zs:
return (strip_zs[:-1] + chr(ord(strip_zs[-1]) + 1) +
'a' * (len(s) - len(strip_zs)))
else:
return 'a' * (len(s) + 1)
(I renamed the function because next() already is a built-in function since
Python 2.6)
The function removes all lowercase "z" letters from the end of the string.
If the rest is empty like for next_alpha("zzz") it returns len(s) + 1 "a"s,
or "aaaa" in the example. If the rest is not empty, e.g for
next_alpha("abcz")
it replaces the last non-"z" character with its successor in the alphabet
>>> chr(ord("c")+1)
'd'
and replaces the trailing "z"s with the same number of trailing "a"s.
> I have found this function works well if I call it directly with a
> string enclosed in quotes:
>
> returnValue = next("abc")
>
> However, if I call the function with a variable populated from a value I
> obtain from an array[] it fails returning only ^K
I'm assuming that something is missing here, but if the function actually
returns the string "^K" that is the expected result for
>>> next_alpha("^J")
'^K'
The function only handles lowercase letters a...z correctly.
> Unfortunately, because I don't fully understand this next function I
> can't really interpret the error.Any help would be greatly appreciated.
What is the actual value you pass to the function? Add print statements
argument = ... # your code
print argument
return_value = next_alpha(argument)
print return_value
and post what is printed.
If you get a traceback, e. g.
>>> next_alpha([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "next_alpha.py", line 2, in next_alpha
strip_zs = s.rstrip('z')
AttributeError: 'list' object has no attribute 'rstrip'
cut and paste it, and post it here, too
More information about the Python-list
mailing list