尝试从用户输入中选择某些字符

时间:2018-02-03 18:33:32

标签: python typeerror

我的目标是将p设置为year的最后两位数字,但是当我运行该程序时,我会获得TypeError: string indices must be integersp = str(year)[2,3]

我尝试在str中取出p = str(year)[2,3]但我得TypeError: 'int' object is not subscriptable

我不确定我能在这做什么。

year_original=int(input("Enter the 4-digit year: "))
month=int(input("Enter the month as a number: "))
day=int(input("Enter the day as a number: "))

if month == 1 or 2:
    year = year_original-1
p = str(year)[2,3]
q = str(year)[0,1]
r = ((month + 9)//12)+1
s = (13*r-1)/5
t = p/4
u = q/4
v = d+p+s+t+u+(5*q)
w=v//7
print(month,day,",",year_original,"is a ",w)

修改 感谢答案,我已经找到并解决了问题。我也完成了代码。

year_original=int(input("Enter the 4-digit year: "))
month=int(input("Enter the month as a number: "))
day=int(input("Enter the day as a number: "))

if month == 1 or 2:
    year = year_original-1
p = str(year)[2:3]
q = str(year)[0:1]
r = ((month + 9)%12)+1
s = (13*r-1)/5
t = int(p)/4
u = int(q)/4
v = int(day)+int(p)+int(s)+int(t)+int(u)+(5*int(q))
w=v%7

if w == 0:
    w = "Sunday"
elif w == 1:
    w = "Monday"
elif w == 2:
    w = "Tuesday"
elif w == 3:
    w = "Wendsday"
elif w == 4:
    w = "Thursday"
elif w == 5:
    w = "Friday"
elif w == 6:
    w = "Saturday"

if month == "1" or "01":
    month = "January"
elif month == "2" or "02":
    month = "Febuary"
elif month == "3" or "03":
    month = "March"
elif month == "4" or "04":
    month = "April"
elif month == "5" or "05":
    month = "May"
elif month == "6" or "06":
    month = "June"
elif month == "7" or "07":
    month = "July"
elif month == "8" or "08":
    month = "August"
elif month == "9" or "09":
    month = "September"
elif month == "10":
    month = "October"
elif month == "11":
    month = "November"
elif month == "12":
    month = "December"

print(month,day,",",year_original,"is a ",w)

1 个答案:

答案 0 :(得分:0)

','创建一个元组,因此year[2,3]year[(2,3)]相同,而python中不支持year[2:4]。而是将year[0,1](和year[0:2]写入.data A: .word -89, 19, 91, -23, -31, -96, 3, 67, 17, 13, -43, -74 .text main: addi $s0, $zero, 0 #set $s0 for sum of positive nums to 0 la $s1, A #set $s1 to array address addi $t0, $s1, 48 #set $t0 to exit point while: beq $s1, $t0, end lw $t1, A($s1) slt $t2, $t1, $zero bne $t2, $zero, else #skips addition step if A at $s1 is negative add $s0, $s0, $t1 else: addi $s1, $s1, 4 j while end: li $v0, 1 move $a0, $s0 syscall li $v0, 10 syscall