我正在尝试编写一个程序,它将打印字符串左栏中的值。
这是我到目前为止所做的:
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循环。我知道中断将使程序在获得其值后立即结束;我把它放在那里因为程序会继续下去。但除此之外,我完全被难倒了。
答案 0 :(得分:4)
当您致电list(str)
时,您将字符串拆分为单个字符。这是因为字符串也是序列。
要将字符串拆分为单独的行,请使用str.splitlines()
method:
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
答案 1 :(得分: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