python v2:查找字符串的第二个空格

时间:2015-02-02 07:47:12

标签: python

y = raw_input("Please type in a sentence consisting three to four words.: ")
d1 = y[0]
d2 = y.find(" ")
d3 = y[d2+1]
d4 = y.find(" ", d3)
d5 = y[d4+1]
print d1+d3+d5

所以我试图打印一个句子的前三个字母,但在d4 = y.find(" ", d3)部分,程序不会将其识别为整数,如果我将其转换为整数,则会导致错误,因为我在基地10。

2 个答案:

答案 0 :(得分:1)

从您的代码中看起来您正试图在句子中打印前三个单词的首字母。请记住,split()返回一个数组:

y = "one two three four"
y = y.split(" ")
print y[0][0],y[1][0],y[2][0]

<强>输出

o t t

答案 1 :(得分:1)

您可以通过拆分功能实现此目的。

y = raw_input("Please type in a sentence consisting three to four words.: ")
print ''.join([i[0] for i in y.split()])

输出:

$ python f.py
Please type in a sentence consisting three to four words.: foo bar foobar
fbf