2017-12-03 6 views
-2

こんにちは私はPython 3.6.1用の関数を作成しようとしています。ここでユーザーは文を挿入でき、出力は各単語の最初の文字になります。とスペース。 ie Hello World - > H. W.文章を分割して最初の大文字だけを取得する機能

私は以下のコードを作成しましたが、正しく動作させることはできません。私は最初の単語の文字のみを取得していて、何とか2番目または3番目の単語などを無視します。

def initials(text): 
    x = "" 
    for text in text.split(): 
      x += text[0].upper()+". " 
      return x 

st= input("give sentance:") 
print(initials(st)) 

のPython 3.6.1(デフォルト、2015年12月、午前13時05分11秒) [GCC 4.8.2]所与の一文に含ま

Linux上:Hello Worldの H.

私は希望期待HW

ありがとう!

+3

インデント解除あなた 'return'声明。関数は現在、 'for'ループの最初の反復の後に戻ります。 –

答えて

-1

あなたのコードは、単純に次のようになります。

sen = input("Please enter a string ") 
sen = sen.split() 
for i in sen: 
    num = i[0] 
    print(num,end="") 

それはあなたの各単語の最初の文字を印刷します!

0

はこれを試してみてください:

def initials(text): 
    text += " " # add a space to the end of text 
    result = "" 
    # str.find returns -1 if the specified string is not found 
    while text.find(" ")>-1: 
     # the if statement gets rid of extra spaces so they are 
     # not included in the initials 
     if text[0] != " ": 
      result += text[0].upper() + ". " 
     text = text[text.find(" ")+1:] 
    return result 

st= input("give sentance:") 
print(initials(st)) 
+0

これは役に立ちます、ありがとう! – anonymous