字符串操作运行时错误python

时间:2017-07-26 09:07:44

标签: python-2.7 runtime-error

输入:3

gandhi
mahatma gandhI
Mohndas KaramChand gandhi

输出:

Gandhi 
M. Gandhi 
M. K. Gandhi 

我写了以下代码:

n =  int(input())


while n > 0  :
  k = raw_input()

  if k.find(" ") != -1:

    final = str(k[0].upper() + '.')


    for i in range(len(k)) :
      if (k[i] == ' ') & (k[i:].find(" ")):
        final += k[i+1].upper() + ". "
      else:
          if(k[i] == ' '):
            final += k[i+1].upper() + k[i+2:].lower()


    n -= 1

    print final[0:len(final)]

 else :
    print  k[0].upper() + k[1:].lower()

我收到了运行时错误。有人可以解释原因吗?

1 个答案:

答案 0 :(得分:0)

试试这段代码。

str = "gandhi mahatma gandhi Mohndas KaramChand gandhi"
temp = ''
for st in str.split():
    if st == 'gandhi':
        temp = temp + ' ' + st.title()
    else:
        temp = temp + ' ' + st[0].upper() + '.'
print temp

根据您的期望输出 - Gandhi M. Gandhi M. K. Gandhi