2011-04-04 111 views
0

我需要编写一些程序,直到程序中断时才能找到空间。无法正常工作的程序

我一直在问题。 我的代码:

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

如果我将输入字符串 “HOLA amigas” 的回报 “HOLA”。 我需要的程序没有一些内置/或进口文件功能。

我只需要使用while/for循环来实现它。

+4

这是一个错字。 http://meta.stackexchange.com/q/196985/232821 – 2013-09-14 18:30:13

回答

0
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 
0

这样做的Python的方式是这样的:

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

split方法拆分串到一个数组,和[0]返回第一个项该阵列。如果您由于某种原因需要索引:

x = raw_input("") 
i = x.index(" ") 
name = x[:i] 
print name 
2

corents拼写错误,第5行向下。

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