How do you get the next string in python?

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?

GEOCHET

20.8k15 gold badges73 silver badges98 bronze badges

asked May 31, 2009 at 17:33

Pietro SperoniPietro Speroni

3,04910 gold badges41 silver badges53 bronze badges

3

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.

answered May 31, 2009 at 17:46

Adam RosenfieldAdam Rosenfield

379k96 gold badges507 silver badges584 bronze badges

2

A different, longer, but perhaps more readable and flexible solution:

def toval(s):
    """Converts an 'azz' string into a number"""
    v = 0
    for c in s.lower():
        v = v * 26 + ord(c) - ord('a')
    return v

def tostr(v, minlen=0):
    """Converts a number into 'azz' string"""
    s = ''
    while v or len(s) < minlen:
        s = chr(ord('a') + v % 26) + s
        v /= 26
    return s

def next(s, minlen=0):
    return tostr(toval(s) + 1, minlen)

s = ""
for i in range(100):
    s = next(s, 5)
    print s

You convert the string into a number where each letter represents a digit in base 26, increase the number by one and convert the number back into the string. This way you can do arbitrary math on values represented as strings of letters.

The ''minlen'' parameter controls how many digits the result will have (since 0 == a == aaaaa).

answered May 31, 2009 at 19:51

Sucks that python doesn't have what ruby has: String#next So here's a shitty solution to deal with alpha-numerical strings:

def next_string(s):
  a1 = range(65, 91)  # capital letters
  a2 = range(97, 123) # letters
  a3 = range(48, 58)  # numbers
  char = ord(s[-1])
  for a in [a1, a2, a3]:
    if char in a:
      if char + 1 in a:
        return s[:-1] + chr(char + 1)
      else:
        ns = next_string(s[:-1]) if s[:-1] else chr(a[0])
        return ns + chr(a[0])

print next_string('abc')  # abd
print next_string('123')  # 124
print next_string('ABC')  # ABD

# all together now
print next_string('a0')   # a1
print next_string('1a')   # 1b
print next_string('9A')   # 9B

# with carry-over
print next_string('9')    # 00
print next_string('z')    # aa
print next_string('Z')    # AA

# cascading carry-over
print next_string('a9')   # b0
print next_string('0z')   # 1a
print next_string('Z9')   # AA0

print next_string('199')  # 200
print next_string('azz')  # baa
print next_string('Zz9')  # AAa0

print next_string('$a')   # $b
print next_string('$_')   # None... fix it yourself

Not great. Kinda works for me.

answered Sep 10, 2012 at 20:06

GroceryGrocery

2,23415 silver badges26 bronze badges

Python next() function returns the next item of an iterator.

Python next() method Syntax

Syntax : next(iter, stopdef)

Parameters : 

  • iter : The iterator over which iteration is to be performed.
  • stopdef : Default value to be printed if we reach end of iterator.

Return : Returns next element from the list, if not present prints the default value. If default value is not present, raises the StopIteration error.

Python next() method Example

Python3

l = [1, 2, 3]

l_iter = iter(l) 

print(next(l_iter))

Output:

1

Example 1: Iterating a list using next() function

Here we will see the python next() in loop. next(l_iter, “end”) will return “end” instead of raising StopIteration error when iteration is complete.

Python3

l = [1, 2, 3

l_iter = iter(l) 

while True:

    item = next(l_iter, "end")

    if item == "end":

        break

    print(item)

Output:

1
2
3

Example 2: Get the next item from the iterator

Python3

list1 = [1, 2, 3, 4, 5]

l_iter = iter(list1)

print("First item in List:", next(l_iter))

print("Second item in List:", next(l_iter))

Output:

First item in List: 1
Second item in List: 2

Example 3: Passing default value to next()

Here we have passed “No more element” in the 2nd parameter of the next() function so that this default value is returned instead of raising the StopIteration error when the iterator is exhausted.

Python3

list1 = [1]

list_iter = iter(list1)

print(next(list_iter))

print(next(list_iter, "No more element"))

Output:

1
No more element

Example 4: Python next() StopIteration

Python3

l_iter = iter([1, 2])

print("Next Item:", next(l_iter))

print("Next Item:", next(l_iter))

print("Next Item:", next(l_iter))

Output:

Next Item: 1
Next Item: 2

---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
Input In [69], in ()
      4 print("Next Item:", next(l_iter))
      5 # this line should raise StopIteration exception
----> 6 print("Next Item:", next(l_iter))

StopIteration: 

While calling out of the range of iterator then it raises the Stopiteration error, to avoid this error we will use the default value as an argument.

Example 5: Performance Analysis

Python3

import time

l = [1, 2, 3, 4, 5]

l_iter = iter(l)

print("[Using next()]The contents of list are:")

start_next = time.time_ns()

while (1):

    val = next(l_iter, 'end')

    if val == 'end':

        break

    else:

        print(val, end=" ")

print(f"\nTime taken when using next()\

is : {(time.time_ns() - start_next) / 10**6:.02f}ms")

print("\n[Using For-Loop] The contents of list are:")

start_for = time.time_ns()

for i in l:

    print(i, end=" ")

print(f"\nTime taken when using for loop is\

: {(time.time_ns() - start_for) / 10**6:.02f}ms")

Output: 

[Using next()]The contents of list are:
1 2 3 4 5 
Time taken when using next() is : 0.23ms

[Using For-Loop] The contents of list are:
1 2 3 4 5 
Time taken when using for loop is : 0.23ms

Conclusion: Python For loop is a better choice when printing the contents of the list than next().

Applications: next() is the Python built-in function for iterating the components of a container of iterator type. Its usage is when the size of the container is not known, or we need to give a prompt when the iterator has exhausted (completed).


How do you get the next letter in a string in Python?

You can use regular expressions: for match in re. findall(r'([a-z])\1', your_string): print('Double letters found here. ')

How do you print the next line in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = , which is the character that will be used to separate the lines.

What does \n and \t do in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

How do you split a line in a string in Python?

Inserting a newline code \n , \r\n into a string will result in a line break at that location. On Unix, including Mac, \n (LF) is often used, and on Windows, \r\n (CR + LF) is often used as a newline code.