如何从 python 中的字符串中获取数字?
How do I get a number from a string in python?
需要帮助的人,
s = "I waited 60 minutes. I cannot wait any longer. My home is 20 miles away."
如何提取旁边有分钟的数字。然后将数字除以 2 并得到下面的字符串作为输出,
“我只等了30分钟。我不能再等了。我家在 20 英里外。”
“60分钟”应该换成“只有30分钟”。不是 60,可以是任何数字。
如果可以的话,声明为f“I waited {myTime (60)} minutes. I cannot wait any longer. My home is 20 miles away.”
。然后你可以简单地改变变量整数 myTime
.
如果您真的必须从原始输入中获取它,我建议您先拆分字符串。然后你可以遍历每个单词并检查 int(word)
是否是一个数字。
正则表达式替换函数最适合该任务
一行
import re
s = "I waited 60 minutes. I cannot wait any longer. My home is 20 miles away."
print(re.sub("(\d+)( minutes)",lambda m:str(int(m.group(1))//2)+m.group(2),s))
打印:
I waited 30 minutes. I cannot wait any longer. My home is 20 miles away.
lambda
函数在输入中输入正则表达式组,它“只是”将第一个参数转换为整数,将其除以 2,然后转换回字符串,并重建时间字符串。
另一种使用for循环的方法,
def isnum(s):
res= False
try:
n = int(s)
res = True
except:
pass
return res
s = "I waited 60 minutes. I cannot wait any longer. My home is 20 miles away."
j = -1
s_list = s.split(' ')
res = ""
for i in s_list:
j += 1
if isnum(i):
if s_list[j+1] in ['minute', 'minute.', 'minutes', 'minutes.']:
i = str(int((int(i)/2)))
res += i + " "
print(res)
需要帮助的人,
s = "I waited 60 minutes. I cannot wait any longer. My home is 20 miles away."
如何提取旁边有分钟的数字。然后将数字除以 2 并得到下面的字符串作为输出,
“我只等了30分钟。我不能再等了。我家在 20 英里外。”
“60分钟”应该换成“只有30分钟”。不是 60,可以是任何数字。
如果可以的话,声明为f“I waited {myTime (60)} minutes. I cannot wait any longer. My home is 20 miles away.”
。然后你可以简单地改变变量整数 myTime
.
如果您真的必须从原始输入中获取它,我建议您先拆分字符串。然后你可以遍历每个单词并检查 int(word)
是否是一个数字。
正则表达式替换函数最适合该任务
一行
import re
s = "I waited 60 minutes. I cannot wait any longer. My home is 20 miles away."
print(re.sub("(\d+)( minutes)",lambda m:str(int(m.group(1))//2)+m.group(2),s))
打印:
I waited 30 minutes. I cannot wait any longer. My home is 20 miles away.
lambda
函数在输入中输入正则表达式组,它“只是”将第一个参数转换为整数,将其除以 2,然后转换回字符串,并重建时间字符串。
另一种使用for循环的方法,
def isnum(s):
res= False
try:
n = int(s)
res = True
except:
pass
return res
s = "I waited 60 minutes. I cannot wait any longer. My home is 20 miles away."
j = -1
s_list = s.split(' ')
res = ""
for i in s_list:
j += 1
if isnum(i):
if s_list[j+1] in ['minute', 'minute.', 'minutes', 'minutes.']:
i = str(int((int(i)/2)))
res += i + " "
print(res)