python在字符串中加入数字_如何在字符串中添加数字

我更喜欢先从数字中删除破折号-,这样可以很容易地处理。你也可以不用像你试过的那样去掉它。在# split it into parts separated by dashes

# consider 4094-3460-2754

no_dashes = number.split('-')

print(no_dashes) # ['4094', '3460', '2754']

# combine the numbers without dashes

no_dashes = ''.join(no_dashes)

print(no_dashes) # 409434602754

# convert it into a list of integers so that it is more easier to work with

number = [int(x) for x in no_dashes]

print(number) # [4, 0, 9, 4, 3, 4, 6, 0, 2, 7, 5, 4]

您可以阅读split()和join()here。在

现在,正如您所提到的,第一个条件很简单,您可以简单地检查第一个数字是否为4。在

^{pr2}$

第二个条件也很简单:# 2nd condition

# 4th digit is a[3] and 5th digit is a[4]

if number[3] != number[4] + 1:

return 'Viloates #2'

对于第三个条件,你只需要找到数字中每个数字的和。由于我们已经将数字转换为整数数组,因此使用sum()函数也很容易:#

你可能感兴趣的:(python在字符串中加入数字)