gpt4 book ai didi

python - Python 中的字符串

转载 作者:行者123 更新时间:2023-11-28 22:53:15 25 4
gpt4 key购买 nike

我是 Python 的法国新手,我想编写一个程序,在时间(字符串“日、时、分、秒”)错误(例如 83 秒)时向我们发出警告。我做了这个程序:

t=input("Put day,hours,minutes,seconds: ")
t="j,h,m,s"
if int(t[6])<=0 or int(t[6])>=59:
print("Seconds wrong")
if int(t[4])<=0 or int(t[4])>=59:
print("Minutes wrong")
if int(t[2])<=0 or int(t[2])>=24:
print("Hours wrong")
if int(t[0])<=0 or int(t[0])>=31:
print("days wrong")
else:
print("OK")

但是我有这个错误:

  if t[6]<=0 or t[6]>=59:
TypeError: unorderable types: str() <= int()

所以我把“int”放在各处(比如 "int(t[X])<=0" )但后来我遇到了这个错误:

  if int(t[6])<=0 or int(t[6])>=59:
ValueError: invalid literal for int() with base 10: 's'

最佳答案

此字符串中没有数字:

t="j,h,m,s"

所以任何尝试做 int(t[anything]) 都会失败。您不能将字符串转换为整数,除非该字符串包含实际整数的字符串表示形式,例如 t = "1234"

此外,即使您有类似 t = "31,11,22,45" 的内容,int(t[6]) 也不会给您秒数,因为秒的表示将位于索引 9 和 10 处。在这种情况下,您需要 t = int(t[9:11])

你要找的就是这样的东西:

#!/usr/bin/python

t = "31,11,22,45"
(day, hour, min, sec) = [int(elem) for elem in t.split(',')]

if not 0 <= sec <= 59:
print("Seconds wrong")
elif not 0 <= min <= 59:
print("Minutes wrong")
elif not 0 <= hour <= 23:
print("Hours wrong")
elif not 1 <= day <= 31:
print("days wrong")
else:
print("OK")

请注意,您需要将除第一个 if 之外的所有内容更改为 elif,否则它将打印 "OK" if day 是正确的,但其他一切都是错误的,或者如果有任何错误,您需要保留某种单独的变量来存储,并在最后检查它,例如以下内容:

#!/usr/bin/python

t = "31,11,22,45"
(day, hour, min, sec) = [int(elem) for elem in t.split(',')]
time_ok = True

if not 0 <= sec <= 59:
print("Seconds wrong")
time_ok = False

if not 0 <= min <= 59:
print("Minutes wrong")
time_ok = False

if not 0 <= hour <= 23:
print("Hours wrong")
time_ok = False

if not 1 <= day <= 31:
print("Days wrong")
time_ok = False

if time_ok:
print("Time is OK")

关于python - Python 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19618489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com