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 循环。我知道 break 会在程序获得价值后立即结束;我把它放在那里是因为程序会继续进行。但除此之外,我完全被难住了。

4

2 回答 2

4

当您调用时,list(str)您将字符串拆分为单个字符。发生这种情况是因为字符串也是序列。

要将字符串拆分为单独的行,请使用以下str.splitlines()方法

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

要打印每行的第一个单词str.split(),请使用to 溢出空格:

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 回答
0

这更容易:

st='''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'''

print('\n'.join(e.split()[0] for e in st.splitlines()))  # first word...

或者:

print('\n'.join(e[0] for e in st.splitlines())) # first letter
于 2013-07-13T18:23:44.853 回答