简体   繁体   English

如何将字符串转换为 integer?

[英]How do i convert a string into an integer?

So for my activity, I want to check if a car number is valid.因此,对于我的活动,我想检查车号是否有效。
To validate a given vehicle plate number with 4 digits starting with 'S', the following must be done:要验证以“S”开头的 4 位数字的给定车牌号,必须执行以下操作:
• Ignore the letter 'S' • 忽略字母“S”
• Assign a number to the letters as follows: A=1, B=2, C=3, …etc. • 为字母分配一个数字,如下所示:A=1、B=2、C=3、……等。 For the number plate SBA 1234, this is converted to 21 1234对于车牌 SBA 1234,这将转换为 21 1234
• The 6 individual numbers need to be multiplied by 9,4,5,4,3,2 respectively and added together. • 6 个单独的数字需要分别乘以 9、4、5、4、3、2 并相加。 For the example above, we will get, 2 x 9 + 1 x 4 + 1 x 5 + 2 x 4 + 3 x 3 + 4 x 2 = 52对于上面的示例,我们将得到 2 x 9 + 1 x 4 + 1 x 5 + 2 x 4 + 3 x 3 + 4 x 2 = 52

At the moment I managed to do the first two points and replace the letters with numbers, but for the part where I need to multiply the numbers respectively , I believe python still reads it(Newnum) as a string so I need to convert it to an integer so they can be multiplied.目前我设法做到了前两点并用数字替换字母,但是对于我需要分别乘以数字的部分,我相信 python 仍然将它(Newnum)作为字符串读取,所以我需要将其转换为一个 integer 以便它们可以相乘。

vehicle_num = input("Enter the vehicle number to be validated: ")
if "S" in vehicle_num:
    Newnum = vehicle_num.replace("S","").replace("A","1").replace("B","2").replace("C","3")
    print(Newnum)
else:
    print("Not working")
multiplynum = Newnum

multiplynum = ((Newnum[0] * 9) + (Newnum[1] * 4) + (Newnum[2] * 5) +
(Newnum[3] * 4) + (Newnum[4] * 3) + (Newnum[5] * 2))
print(Newnum)

Simply int(your_string) should work, if your string doesn't have any other special characters.如果您的字符串没有任何其他特殊字符,则只需int(your_string)

Like this:像这样:

vehicle_num = input("Enter the vehicle number to be validated: ")
if "S" in vehicle_num:
    Newnum = vehicle_num.replace("S","").replace("A","1").replace("B","2").replace("C","3")
    print(Newnum)
else:
    print("Not working")

Newnum = list(map(int, Newnum))

multiplynum = ((Newnum[0] * 9) + (Newnum[1] * 4) + (Newnum[2] * 5) +
(Newnum[3] * 4) + (Newnum[4] * 3) + (Newnum[5] * 2))
print(Newnum)

ord will for here. ord会在这里。 Because it converts the character to its ascii equivalent.因为它将字符转换为其 ascii 等价物。 We then subtract enough so that A=1, B=2 etc.然后我们减去足够的量,使 A=1,B=2 等。

def solve(vehicle_num):
    if vehicle_num[0] != 'S':
        return 'Not Working'
    vehicle_num = [ord(x) - 64 if not x.isdigit() else int(x) for x in vehicle_num[1:].replace(' ', '')]
    return sum([x * y for x, y in zip([9, 4, 5, 4, 3, 2], vehicle_num)])


print(solve('SBA 1234'))

#Output
52

You can use various functions and methods to make it more concise:您可以使用各种函数和方法使其更简洁:

from string import ascii_uppercase

def convert(s, *, factors=(9, 4, 5, 4, 3, 2)):
    letters, numbers = s.split()
    letters = letters[1:]  # ignore prefix 'S'
    table = {x: i for i, x in enumerate(ascii_uppercase, start=1)}
    letters = [table[x] for x in letters]  # replace letters with numbers
    numbers = [int(x) for x in numbers]
    return sum(x*y for x, y in zip(letters + numbers, factors))

I'm writing this answer in a way that you could get some other benefit from it apart from just this problem.我写这个答案的方式除了这个问题之外,你还可以从中获得一些其他好处。 This solution doesn't catch all errors and can be much improved but I guess you just need a starting point.该解决方案无法捕获所有错误并且可以得到很大改进,但我想您只需要一个起点。

vehicle_num = input("Enter the vehicle number to be validated: ")

trimmed_vnum = [n for n in vehicle_num if n not in ['S', ' ']] # list comprehension, ternary operator
letter_to_num = {'A': 1, 'B': 2, 'C': 3} # dictionary

converted_num = []
for n in trimmed_vnum:
    if n in letter_to_num:
        n = letter_to_num[n]
    else:
        n = int(n) # explicit type conversion
    converted_num.append(n)

multiplier = [9,4,5,4,3,2]

if len(converted_num) == len(multiplier):
    final = sum([a*b for a,b in zip(converted_num, multiplier)]) # zip, list comprehension

print(final)

In answer to the specific question, you would use int(value) for the type conversion.在回答特定问题时,您将使用int(value)进行类型转换。

As an aside, you might also consider using a regular expression to validate whether your vehicle number has the expected format and to extract the relevant data items from it.顺便说一句,您还可以考虑使用正则表达式来验证您的车辆编号是否具有预期的格式并从中提取相关数据项。 For example:例如:

import re

vehicle_num = "SBA1234"
multipliers = [9, 4, 5, 4, 3, 2]

m = re.match("S(?P<letters>[A-Z]{2}) *(?P<digits>[0-9]{4})$", vehicle_num)

if m:
    values = ([ord(char) - ord('A') + 1 for char in m.group('letters')] +
              [int(char) for char in m.group('digits')])

    print(sum(mult * value for mult, value in zip(multipliers, values)))

else:
    print('Does not match the expected pattern')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM