📜  Python程序将数字移动到字符串的末尾

📅  最后修改于: 2022-05-13 01:55:41.029000             🧑  作者: Mango

Python程序将数字移动到字符串的末尾

给定一个字符串,任务是编写一个Python程序将其中的所有数字移动到它的末尾。

例子:

方法 1:使用isdigit()循环

在此,我们使用 isdigit() 检查元素和数字,跟踪所有数字并在迭代后的字符串末尾追加。

Python3
# initializing string
test_str = 'geek2eeks4g1eek5sbest6forall9'
  
# printing original string
print("The original string is : " + str(test_str))
  
# getting all numbers and removing digits
res = ''
dig = ''
for ele in test_str:
    if ele.isdigit():
        dig += ele
    else:
        res += ele
  
# adding digits at end
res += dig
  
# printing result
print("Strings after digits at end : " + str(res))


Python3
# initializing string
test_str = 'geek2eeks4g1eek5sbest6forall9'
  
# printing original string
print("The original string is : " + str(test_str))
  
# getting all numbers
dig = ''.join(ele for ele in test_str if ele.isdigit())
  
# getting all elements not digit
res = ''.join(ele for ele in test_str if not ele.isdigit())
  
# adding digits at end
res += dig
  
# printing result
print("Strings after digits at end : " + str(res))


输出:

方法 2:使用join()  

在这种情况下,我们执行提取数字并使用单独的推导忽略它们然后加入两者的任务。最后,数字字符串连接到实际字符串的末尾。

蟒蛇3

# initializing string
test_str = 'geek2eeks4g1eek5sbest6forall9'
  
# printing original string
print("The original string is : " + str(test_str))
  
# getting all numbers
dig = ''.join(ele for ele in test_str if ele.isdigit())
  
# getting all elements not digit
res = ''.join(ele for ele in test_str if not ele.isdigit())
  
# adding digits at end
res += dig
  
# printing result
print("Strings after digits at end : " + str(res))

输出: