5 Best Ways to Move Numbers to the End of the String in Python

πŸ’‘ Problem Formulation: In many programming scenarios, there’s a need to organize string data by separating characters and numbers – often by moving the numbers to the end of the string. For example, given the input 'foo4bar99baz', the desired output is 'foobarbaz499'. This article explores various Pythonic ways to achieve this string manipulation.

Method 1: Using Loops

This method splits the string into characters and numbers using simple loops. Every character is examined; if it’s a number, it’s moved to the end of the result string, otherwise, it’s placed at the current position. The function ensures all characters remain in their original order, with numbers trailing behind.

Here’s an example:

def move_numbers_to_end(input_string):
    letters = ""
    numbers = ""
    for character in input_string:
        if character.isdigit():
            numbers += character
        else:
            letters += character
    return letters + numbers

result = move_numbers_to_end("Hello2World5")
print(result)

Output:

HelloWorld25

This code defines a function move_numbers_to_end() that takes a string, iterates through each character, and categorizes them into letters and numbers, finally concatenating and returning the modified string.

Method 2: Using Regular Expressions

Regular Expressions (regex) provide a powerful way to search and manipulate strings. This method uses regex to find all numbers and then reposition them to the end of the string. It’s a concise and efficient way to handle the separation of numbers and characters without manually iterating over each character.

Here’s an example:

import re

def move_numbers_to_end_regex(input_string):
    numbers = re.findall(r'\\d+', input_string)
    no_numbers = re.sub(r'\\d+', '', input_string)
    return no_numbers + ''.join(numbers)

result = move_numbers_to_end_regex("3ApplesAnd5Oranges")
print(result)

Output:

ApplesAndOranges35

The move_numbers_to_end_regex() function utilizes the re.findall() method to extract all numbers, and re.sub() to remove them from the string. The resulting strings are then concatenated, moving all the numbers to the end.

Method 3: Using List Comprehension

List comprehensions offer a succinct way to create lists in Python. By using list comprehension in conjunction with the join() function, this method first segregates characters and digits into separate lists and then combines them in the correct order for the desired output.

Here’s an example:

def move_numbers_to_end_list(input_string):
    return ''.join([c for c in input_string if not c.isdigit()]) + \
           ''.join([c for c in input_string if c.isdigit()])

result = move_numbers_to_end_list("Data2021Science")
print(result)

Output:

DataScience2021

This snippet combines two list comprehensions: the first selects the non-digit characters, and the second selects the digit characters. By concatenating the outputs, the numbers are effectively moved to the end of the string.

Method 4: Using Partitioning

This approach partitions the string into non-digit characters and digits by using partitioning functions. Although not as common, it provides another logical way to solve the problem by splitting the string and then reconstructing it with numbers at the end.

Here’s an example:

def move_numbers_to_end_partition(input_string):
    parts = re.split('(\\d+)', input_string)
    numbers = ''.join(part for part in parts if part.isdigit())
    letters = ''.join(part for part in parts if not part.isdigit())
    return letters + numbers

result = move_numbers_to_end_partition("mix4and7match")
print(result)

Output:

mixandmatch47

This code uses a re.split() function to separate digits and non-digits into parts and then reconstructs the string by concatenating non-digit parts followed by digit parts.

Bonus One-Liner Method 5: Using Lambda and Sorted

This bonus one-liner demonstrates Python’s ability to concisely solve problems. By using the sorted() function with a custom key, this one-liner moves all the numerical characters to the end of the string in a highly Pythonic fashion.

Here’s an example:

move_numbers_to_end_one_liner = lambda s: ''.join(sorted(s, key=str.isdigit))

result = move_numbers_to_end_one_liner("fun4coding123")
print(result)

Output:

funcoding4123

This snippet uses a lambda function that sorts the string’s characters, ensuring that the digits come after the alphabet. It leverages the fact that sorted() is stable and str.isdigit() returns True for digits.

Summary/Discussion

Method 1: Using Loops. Easy to understand. Can be slow for long strings due to string concatenation in a loop.

Method 2: Using Regular Expressions. Fast and clean. Requires understanding of regex, which may be complex for beginners.

Method 3: Using List Comprehension. Pythonic and concise. Involves two passes over the string, which could be optimized.

Method 4: Using Partitioning. Less common and may look complicated. Avoids multiple concatenations making it potentially more efficient.

Method 5: Bonus One-Liner. Extremely concise. Relies on the stability of sort and may be less straightforward for readability and maintenance.