首页 > 解决方案 > 用字符串作为参数延迟python中的程序

问题描述

我正在尝试制作一个程序,其中包括从用户那里获取输入并使用该输入来延迟程序,但我无法弄清楚如何使用该输入,因为 Time.sleep() 只接受 int 或 float 作为参数,但我需要一个像 time.sleep() 这样延迟程序但将字符串作为参数的函数。

这是程序:现在用户给出的输入存储在 t 变量中,所以我需要一些可以将 t 作为参数的函数。

import webbrowser
import time

print "This is the take a break program"
t= raw_input("In how much time will you take a break? \n")
print ("%s,seconds"%t)
time.sleep(t)
webbrowser.open("youtube.com")

标签: python-2.7

解决方案


您可以在 python 中将字符串转换为 int/float,只需执行以下操作:

#Let say this is your String
String mystring = "100"

#This will convert your string to int
int time = int(mystring)

#And this will convert it to a float
float timeFloat = float(mystring)

请记住检查您的用户输入,因为如果字符串仅由字母组成,它将无法按预期工作。


推荐阅读