引数fullnameをとり、fullnameの頭文字を取り、大文字で出力するPython関数を作成しました。しかし、私のコードには問題があります。これは2つの名前でしか動作しません。フルネームにミドルネーム、つまりDaniel Day Lewisがある場合、それは中断されます。ここで名前の頭文字を大文字にして返す関数
は、私が試したものです:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
second = name_list[1][0]
return(first.upper() + second.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
明らかにこの試みは、2つの変数のみ、最初の名前のための1と2番目の名前のための1つを含んでいます。私はこのような3番目の変数、追加した場合:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
second = name_list[1][0]
third = name_list[2][0]
return(first.upper() + second.upper() + third.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
を私が取得:もちろん
IndexError: list index out of range on line 10
(ライン)で
third = name_list[2][0]
を私はフルネームを変更した場合、この機能は動作しません「オジー・スミス・ジュニア」。しかし、私の機能は、フルネームに1,2,3、または4の名前があるかどうかに関係なく機能しなければなりません。私はPythonで「フルネームは、2番目の名前または第三の名称又は第四の名前を持っている場合、大文字のイニシャルを返す」と言うにはどうすればよい
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
#if fullname has a second name:
second = name_list[1][0]
#if fullname has a third name:
third = name_list[2][0]
#if fullname has one name:
return(first.upper())
#if fullname has two names:
return(first.upper() + second.upper())
#if fullname has three names:
return(first.upper() + second.upper() + third.upper())
#if fullname has three names:
return(first.upper() + second.upper() + third.upper + fourth.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
:私のような何かを言う必要がありますか?または私は正しい軌道にいるのですか?ありがとうございました。
おかげで
upper
1のショットを行う第一、すべての頭文字に参加することができます動作するはずです、私はしませんでしたそのようなイニシャルを追加すると思います。なぜ "name for name_list:"という名前が各文字とは違って、それぞれの名前を通って行くのか説明できますか? – Sean'xs.split()'関数は文字列ではなく 'list'を返し、' name_list'は '[" John "、" Smith "]'と等しくなるからです。そのため、 'for name_list'ステートメントは、文字列内の各文字ではなく、リスト項目を1つずつ順番に処理します。 – Mike
ありがとうございます! – Sean