Python程序将数字移动到字符串的末尾
给定一个字符串,任务是编写一个Python程序将其中的所有数字移动到它的末尾。
例子:
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.
方法 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))
输出:
The original string is : geek2eeks4g1eek5sbest6forall9
Strings after digits at end : geekeeksgeeksbestforall241569
方法 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))
输出:
The original string is : geek2eeks4g1eek5sbest6forall9
Strings after digits at end : geekeeksgeeksbestforall241569