无法正常工作的程序

2024-04-23 09:17:10 发布

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

我需要写一些程序,它计数,直到它找到空间,当它找到空间的程序中断工作。你知道吗

我一直是个问题。 我的代码:

x  = raw_input("")
i = 0
corents = 0
while(x[i] != " "):
    corennts +=i
    i+=1
name = x[:corents]
print name

如果我输入字符串“Hola amigas”,它将返回“Hola”。 我需要没有一些内置/或导入文件功能的程序。你知道吗

我只需要用while/for循环来实现它。你知道吗


Tags: 字符串代码name程序inputraw空间内置
3条回答

Python的方式是这样的:

x = raw_input("")
name = x.split(" ")[0]
print name

split方法将字符串拆分为一个数组,[0]返回该数组的第一项。如果出于某种原因需要索引:

x = raw_input("")
i = x.index(" ")
name = x[:i]
print name
x = raw_input()
name = x.split(' ', 1)[0]
print name

或者

x = raw_input()
try:
    offs = x.index(' ')
    name = x[:offs]
except ValueError:
    name = x    # no space found
print name

corents拼写错误,第5行。你知道吗

x  = raw_input("")
i = 0
corents = 0
while(x[i] != " "):
    corents +=i
    i+=1
name = x[:corents]
print name

相关问题 更多 >