📜  用 K 递增数字字符串的Python程序

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

用 K 递增数字字符串的Python程序

给定字符串列表,编写一个Python程序,以 K 递增数字字符串。

例子:

方法 #1:使用str() + int() + loop + isdigit()

在这里,我们使用 str() + int() 执行元素相互转换的任务,并使用 isdigit() 检查数字,使用循环完成迭代。

Python3
# Python3 code to demonstrate working of
# Increment Numeric Strings by K
# Using str() + int() + loop + isdigit()
  
# initializing Matrix
test_list = ["gfg", "234", "is", "98", "123", "best", "4"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 6
  
res = []
for ele in test_list:
  
    # incrementing on testing for digit.
    if ele.isdigit():
        res.append(str(int(ele) + K))
    else:
        res.append(ele)
  
# printing result
print("Incremented Numeric Strings : " + str(res))


Python3
# Python3 code to demonstrate working of
# Increment Numeric Strings by K
# Using list comprehension + isdigit()
  
# initializing Matrix
test_list = ["gfg", "234", "is", "98", "123", "best", "4"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 6
  
# increment Numeric digits.
res = [str(int(ele) + K) if ele.isdigit() else ele for ele in test_list]
  
# printing result
print("Incremented Numeric Strings : " + str(res))


输出:

方法 #2:使用列表理解+ isdigit()

这是可以执行此任务的方法之一。与上面类似,只需一行替代使用列表理解来压缩解决方案。

蟒蛇3

# Python3 code to demonstrate working of
# Increment Numeric Strings by K
# Using list comprehension + isdigit()
  
# initializing Matrix
test_list = ["gfg", "234", "is", "98", "123", "best", "4"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 6
  
# increment Numeric digits.
res = [str(int(ele) + K) if ele.isdigit() else ele for ele in test_list]
  
# printing result
print("Incremented Numeric Strings : " + str(res))

输出: