如何找到多个字符串的len()?

时间:2019-04-15 17:55:10

标签: python python-3.x

我需要找到多个字符串的len()。

current_year = input ("What year is it?")

current_year = int(current_year)

birth_year = input ("What year were you born in?")

birth_year = str(birth_year)

if len(birth_year) != 4:
    print ("Please make your year of birth 4 digits long.")
else:
    birth_year = int(birth_year)
    print("You are " + str(current_year  -  birth_year) + " years old.")

我想包含birth_year的len()。

2 个答案:

答案 0 :(得分:1)

使用elif语句检查当前年份输入。

current_year = input ("What year is it?")    
birth_year = input ("What year were you born in?")

if len(birth_year) != 4:
    print ("Please make your year of birth 4 digits long.")
elif len(current_year) != 4:
    print ("Please make the current year 4 digits long.")
else:
    birth_year = int(birth_year)
    current_year = int(current_year)
    print("You are " + str(current_year  -  birth_year) + " years old.")

不需要birth_year = str(birth_year),因为input()总是返回一个字符串。

您可能应该在try/except的调用周围包含int()代码,这样,如果他们输入的年份实际上不是数字,则可以打印错误。

答案 1 :(得分:1)

这是一种获取所需内容的方法,它更具动态性。使用此基本功能,如果用户输入了不合适的字符串,将要求他们重试。您甚至可以添加一行以检查年份是否在当前年份之后。

请注意,这里有一个循环,其中的出口没有约束。如果要实现此目的,我还将添加一个计数器,该计数器将终止进程以防止无限循环。

def get_year(input_string):

    # Set loop control Variable
    err = True

    # while loop control variable = true
    while err == True:

        # get input
        input_year = input(input_string + '  ')

        # Ensure format is correct        
        try:

            # Check length
            if len(input_year) == 4:

                # Check Data type
                input_year = int(input_year)

                # if everything works, exit loop by changing variable
                err = False

        # if there was an error, re-enter the loop
        except:

            pass

    # return integer version of input for math
    return input_year

# set variables = function output
birth_year = get_year('What year were you born? Please use a YYYY format!\n')
current_year = get_year('What is the current year? Please use a YYYY format!\n')

# print output displaying age
print("You are " + str(current_year  -  birth_year) + " years old.")