简体   繁体   English

如何提取输入的特定部分?

[英]How can I extract a specific part of an input?

First of all I am making some sort of timer (you'll know why I say this).首先,我正在制作某种计时器(你会知道我为什么这么说)。 I have a class and each parameter takes an integer as input.我有一个类,每个参数都接受一个整数作为输入。 Now, whenever I ask the user to input a value (for example, they could input "3hrs 2mins 1s") I want to get the numbers;现在,每当我要求用户输入一个值(例如,他们可以输入“3hrs 2mins 1s”)时,我都想获取数字; but that's not the matter.但这不是问题。 The matter is that idk how I could get rid of those words, like getting rid of "hrs" so I can just take the number (eventually I would have to convert it into a int).问题是我知道我如何摆脱这些词,比如摆脱“小时”,这样我就可以取数字(最终我不得不将它转换成一个整数)。 Any ideas?有任何想法吗? Hope I was clear.希望我很清楚。

You can use a regular expression to match the numbers only.您可以使用正则表达式仅匹配数字。 Using re.findall() you can get a list of results that match the given regular expression.使用re.findall()可以获得与给定正则表达式匹配的结果列表。

import re

user_input = '11hrs 2mins 1s'           # You can use `input()`
time = re.findall('\d+', user_input)    # Find all results
time = [int(i) for i in time]           # Convert each of the numbers to digits

print(time)

Here, \\d means any digit and + means occurring more than once.这里, \\d表示任何数字, +表示出现多次。 Thus using findall() function you get a list of numbers captured within the string.因此,使用findall()函数,您可以获得字符串中捕获的数字列表。

Output输出


[11, 2, 1]

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

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