0

文字列の左の列から値を出力するプログラムを作成しようとしています。

これは私がこれまでに持っているものです:

str = '''Dear Sam:
From Egypt we went to Italy, and then took a trip to Germany, Holland and England.
We enjoyed it all but Rome and London most.
In Berlin we met Mr. John O. Young of Messrs. Tackico & Co., on his way to Vienna.
His address there is 147 upper Zeiss Street, care of Dr. Quincy W. Long.
Friday the 18th, we join C. N. Dazet, Esquire and Mrs. Dazet, and leave at 6:30 A.M. for Paris
on the 'Q. X.' Express and early on the morning on the 25th of June start for home on the S. S. King.
Very sincerely yours,
Signature of writer'''

splitstr = list(str)
while "True" == "True":
    for i in splitstr:
        left_column = splitstr[0:1]
        print(left_column)
        break

出力は次のとおりです。

["D"]

私はまだそれを理解する過程にありますが、while ループとおそらく for ループが必要であることはわかっています。ブレークによって、プログラムが値を取得した直後にプログラムが終了することはわかっています。プログラムがそのまま続くので、そこに置きました。しかし、それ以外に、私は完全に困惑しています。

4

2 に答える 2

4

呼び出すときlist(str)に、文字列を個々の文字に分割します。これは、文字列もシーケンスであるためです。

文字列を別々の行に分割するには、次のstr.splitlines()メソッドを使用します。

for line in somestring.splitlines():
    print line[0]  # print first character

各行の最初の単語str.split()を出力するには、空白にこぼれるように使用します。

for line in somestring.splitlines():
    print line.split()[0]  # print first word

または、一度だけ分割することでもう少し効率的に:

for line in somestring.splitlines():
    print line.split(None, 1)[0]  # print first word
于 2013-07-13T18:03:39.480 に答える