Python Program to move numbers to the end of the string
Given a string, the task is to write a Python program to move all the numbers in it to its end.
Examples:
Input : test_str = ‘geek2eeks4g1eek5sbest6forall9’
Output : geekeeksgeeksbestforall241569
Explanation : All numbers are moved to end.Input : test_str = ‘geekeeksg1eek5sbest6forall9’
Output : geekeeksgeeksbestforall1569
Explanation : All numbers are moved to end.
Method 1 : Using isdigit() and loop
In this, we check elements and digits using isdigit(), keeping track of all the numbers and append at end of string post iteration.
Python3
# initializing stringtest_str = 'geek2eeks4g1eek5sbest6forall9'# printing original stringprint("The original string is : " + str(test_str))# getting all numbers and removing digitsres = ''dig = ''for ele in test_str: if ele.isdigit(): dig += ele else: res += ele# adding digits at endres += dig# printing resultprint("Strings after digits at end : " + str(res)) |
Output:
The original string is : geek2eeks4g1eek5sbest6forall9
Strings after digits at end : geekeeksgeeksbestforall241569
Method 2 : Using join()
In this, we perform the task of extracting digits and ignoring them using separate comprehensions and then joining both. At the end, digit string is joined at end of actual string.
Python3
# initializing stringtest_str = 'geek2eeks4g1eek5sbest6forall9'# printing original stringprint("The original string is : " + str(test_str))# getting all numbersdig = ''.join(ele for ele in test_str if ele.isdigit())# getting all elements not digitres = ''.join(ele for ele in test_str if not ele.isdigit())# adding digits at endres += dig# printing resultprint("Strings after digits at end : " + str(res)) |
Output:
The original string is : geek2eeks4g1eek5sbest6forall9
Strings after digits at end : geekeeksgeeksbestforall241569
Method 3: Without using any built-in method.
Python3
# initializing stringtest_str = 'geek2eeks4g1eek5sbest6forall9'# printing original stringprint("The original string is : " + str(test_str))digits="0123456789"# getting all numbers and removing digitsres = ''dig = ''for ele in test_str: if ele in digits: dig += ele else: res += ele# adding digits at endres += dig# printing resultprint("Strings after digits at end : " + str(res)) |
The original string is : geek2eeks4g1eek5sbest6forall9 Strings after digits at end : geekeeksgeeksbestforall241569
The time and space complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4: Using isnumeric() method
Python3
# initializing stringtest_str = 'geek2eeks4g1eek5sbest6forall9'# printing original stringprint("The original string is : " + str(test_str))# removing digitsres = ''dig = ''for ele in test_str: if ele.isnumeric(): dig += ele else: res += ele# adding digits at endres += dig# printing resultprint("Strings after digits at end : " + str(res)) |
The original string is : geek2eeks4g1eek5sbest6forall9 Strings after digits at end : geekeeksgeeksbestforall241569


