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 <br>the S. S. King.
Very sincerely yours,
Signature of writer'''

splitstr = list(str)
list_a = []
list_b = []

for i in splitstr:
    if i == '\n':
        list_a.append(list_b)
        list_b = []
    else:
        list_b.append(i)

    for i in list_a:
       left_column = list_b[:1]
       print(left_column)
       break

此代码确实打印出左列中的字母,但打印次数过多。输出应该类似于

['D','F','W','I','H','F','o','V','S']

也可以是垂直的,没关系。

4

1 回答 1

3

真的不需要这些,为什么不做类似的事情:

text = '''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 [line[0] for line in text.splitlines()]
['D','F','W','I','H','F','o','V','S']

另外,不要str用作变量名,因为这已经是内置函数的名称。

于 2013-07-14T02:16:55.723 回答