2016-11-18 5 views
-2

次の手順を実行する方法をより明確に説明します。 Pythonでインデックスの使用方法の理解

# loop while i is less than the length of name and the i-th character is not a space. 
# return the part of name up to but not including the i-th character to the caller. 
def get_first_name(name): 
    i = 0 
    while i < len(name) and '' in str(i): 
     i += 1 
    return name 
+0

*「i番目の文字」*は、インデックス「i」の文字、つまり「名前[i]」です。 Pythonの文字列をインデックスで繰り返し処理するのは通常不要です。代わりに 'for char in name:'を使って各文字を取得することができます。 – jonrsharpe

答えて

0

私はあなたの機能を実現するが、私はこれはあなたのいくつかの運動の一環と考えているとしてだけでロジックを説明するわけではありません。

あなたの条件は以下のように書くことができます。印刷された

name = "Hello World" 
i = 0 

# len(name): will return the length of `name` string 
# name[i] != " ": will check that item at `i`th position is not blank space 

while i < len(name) and name[i] != " ": 
    print name[:i+1] # print string from start to the `i`th position 
    i += 1 

:、私はあなたがあなたの関数にこのロジックを置く方法を知っていると思います今

H 
He 
Hel 
Hell 
Hello 

をして返却する値;)

+0

アドバイスをいただきありがとうございます。 –

+0

私は、質問をしている人に彼の質問をより良く知ってもらうのを手伝ってくれるのを知ってうれしいです。ちょうど冗談:Dあなたがあなたの任務を意味していることを質問で知っています;) –

0

文字列を使用すると、インデックスname[i]のような表記を使用することができます配列です。したがって、文字を文字ごとにループし、空白文字' 'と比較し続けることができます。スペースではない文字を押すたびに、一時的な文字列に追加します。空白になったら、ループを止め、一時的な文字列の値がファーストネームを表します。

def get_first_name(name): 
    first = '' 
    i = 0 
    while i < len(name) and name[i] != ' ': 
     first += name[i] # append this letter 
     i += 1   # increment the index 
    return first 

>>> get_first_name('John Jones') 
'John' 
0

アドバイスいただきありがとうございます。私が必要とする仕様に準拠したコードを手に入れることができました。

# Function designed to retrieve first name only from fullname entry. 
def get_first_name(name): 
    i = 0 
    while i < len(name) and name[i] !=" ": 
     i += 1 
    return name[:i] 

# Function designed to retrieve first initial of last name or first initial of first name if only one name input. 
def get_last_initial(name): 
    j = len(name) - 1 
    while j >= 0 and name[j] !=" ": 
     j-=1 
    return full_name[j+1] 

# Function that generates username based upon user input. 
def get_username(full_name): 
    username = get_first_name(full_name) + get_last_initial(full_name) 
    return username.lower() 
関連する問題