Python 查找字符串中空格以外的字母

Python 查找字符串中空格以外的字母,python,python-2.7,Python,Python 2.7,我试图打印一个句子前三个单词的前几个字母,但在d4=y.find(“,d3)部分,程序没有将其识别为整数,如果我将其转换为整数,则会导致错误,因为我在10进制 我如何解决这个问题 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+

我试图打印一个句子前三个单词的前几个字母,但在
d4=y.find(“,d3)
部分,程序没有将其识别为整数,如果我将其转换为整数,则会导致错误,因为我在10进制

我如何解决这个问题

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

从你的代码看,你似乎在试图打印一个句子中前三个单词的首字母缩写。请记住,
split()
返回一个数组:

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

o t t

您可以通过split函数实现这一点

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

“我正试图打印一个句子的前三个字母”-你的意思是:我正试图打印一个句子中前三个单词中每一个的第一个字母吗?你在
d4=y.find(“,d3)
中得到一个错误,因为find方法需要一个索引作为第二个参数,但是你传递了一个字符。很好!唯一的问题是它将打印输入的所有首字母,而不是前三个单词的首字母。