如何打印第二个数字及其位置

2024-09-28 22:54:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是编写一个脚本,将第二个数字写入s并将其位置写入标准输出

输入示例:

afg 456 gg 677

示例输出:

 677 12

除了print部分之外,我的代码都是正确的-它打印的是第一个数字及其位置,而不是第二个:

s = input()
i = 0

while i < len(s) and (s[i] < "0" or "9" < s[i]):
    i = i + 1

if i < len(s):

    j = i
    while j < len(s) and "0" <= s[j] and s[j] <= "9":
        j = j + 1

    print(s[i:j], len(s[0:i]))

Tags: orand代码脚本示例input标准len
1条回答
网友
1楼 · 发布于 2024-09-28 22:54:47

我想这是一个有限制的家庭作业吧?因此,这里有一个愚蠢而有教育意义的例子。只需增加计数器i并再次运行相同的循环:

s = input()
i = 0
j = 0

# looking for the first num
while i < len(s) and (s[i] < "0" or "9" < s[i]): i = i + 1

if i < len(s):
    j = i
    while j < len(s) and "0" <= s[j] and s[j] <= "9":  j = j + 1

# increase counter
i = i + j

# run again for the second num
if i < len(s):
    while i < len(s) and (s[i] < "0" or "9" < s[i]): i = i + 1

    if i < len(s):
        j = i
        while j < len(s) and "0" <= s[j] and s[j] <= "9":  j = j + 1

print(s[i:j], len(s[0:i]))

不是为了现实生活

相关问题 更多 >