我的计算机科学课上有一个项目,其中一部分需要知道一个人的身高。 我想让它问"你的身高是多少?(格式如 ft'in"):"并将输入转换为英寸,但我不知道该怎么做。 有什么帮助吗?
您可以使用regex
来解析ft' in"
格式的任何变体:
import re
pattern = re.compile(r"""(d+)' *(d+)(?:"|'')?""")
text = input("What is your height? ")
feet, inches = map(int, re.match(pattern, text).groups())
下面是正则表达式(d+)' *(d+)(?:"|'')?
的作用:它匹配撇号左侧的一组(非空)数字,后跟零个或多个空格,以及另一组数字,后跟可选的双撇号("
或''
)。请注意,由于我们需要在模式字符串中"
文字,因此将其括在三重双引号中。
使用正则表达式的优点是,如果您的格式稍后变得更加复杂(例如,撇号之间的空格数量可变,可能缺少撇号等),则更容易适应,因为您已经准备好了一切。此外,您甚至可以进行一些错误检查:
import re
heightPattern = re.compile(r"""(d+)' *(d+)(?:"|'')?""")
def parseHeight() -> (int, int):
text = input("What is your height? ")
match = re.match(heightPattern, text)
if not match:
raise ValueError("Couldn't parse height")
feet, inches = map(int, match.groups())
return feet, inches
最后,您只需这样做即可将其全部转换为英寸
inches += 12*feet
因此,总英寸数将存储在inches
中。
我想你要问的是"我如何获取他们的文本输入并将其转换为数字?
我也不知道你用的是什么语言,但让我们假设你使用的是Python,从你放在东西上的标签。
我最喜欢的解析输入的方法是使用正则表达式,请参阅 re 库。
像这样:
import re
txt = input("What is your height? (format like ft'in"):")
search_results = re.search("^([0-9]+)'([0-9]+)"$")
if search_results:
print("feet: " + int(search_results.group(1))
print("inches: " + int(search_results.group(2))
else:
print("You didn't format it correctly")
完全披露,我没有尝试上述代码的正确性或运行它。就像指向正确方向的指针:)
你可以得到一根绳子,分成英尺和英寸
text = input("Enter your height: ") # Format should be <int>"<int>'
feet = int(text.split(""")[0])
inch = int(text.split(""")[1].split("'")[0])
这是一个非常简单的 Python3 代码,没有正则表达式:
h = input('Enter height in ft'in": ') # ask for input
h_split = h.split(''') # break string into 2 parts where single quote occurs
ft, inch = (h_split[0], h_split[1].split('"')[0]) # extract inches in a similar way
ft = int(ft) # convert feet to integer
inch = int(inch) # convert inches to integer
height = ft*12 + inch # convert feet to inches and add inches
print(f'Height in inches: {height}') # For Python2 use print 'Height in inches: ' + str(height)
祝你好运!
你绝对不需要正则表达式来解析它。只要split
绳子!
text = input("Input height:")
Ft, In = text.split("'") # "1'2"" -> ['1', '2"']
result = int(Ft) * 12 + int(In.strip()[:-1]) # get rid of the trailing double quote with `[:-1]`
print(f'You are {result} inches tall')