Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the next string, in alphanumeric ordering, in Python?

Tags:

python

string

I need a simple program that given a string, returns to me the next one in the alphanumeric ordering (or just the alphabetic ordering).

f("aaa")="aab"
f("aaZ")="aba"

And so on.

Is there a function for this in one of the modules already?

like image 763
Pietro Speroni Avatar asked May 31 '09 17:05

Pietro Speroni


People also ask

How do you get the next string in Python?

Python next() function is used to fetch next item from the collection. It takes two arguments an iterator and a default value and returns an element. This method calls on iterator and throws an error if no item is present. To avoid the error, we can set a default value.

How do you find the order of alphabets in Python?

A simple approach: Store the string to a character array and sort the array. If the characters in the sorted array are in the same order as the string then print 'In alphabetical order '. Print 'Not in alphabetical order' otherwise.

How do you sort a list alphabetically and numerically in Python?

Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.


2 Answers

I don't think there's a built-in function to do this. The following should work:

def next_string(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)

Explanation: you find the last character which is not a z, increment it, and replace all of the characters after it with a's. If the entire string is z's, then return a string of all a's that is one longer.

like image 119
Adam Rosenfield Avatar answered Oct 08 '22 17:10

Adam Rosenfield


Are the answers at How would you translate this from Perl to Python? sufficient? Not 100% what you're asking, but close...

like image 45
Alex Martelli Avatar answered Oct 08 '22 17:10

Alex Martelli