[英]Python 3.x - how do get the values of the left column of a string
I am trying to write a program that will print the values from the left column of a string. 我正在尝试编写一个程序,该程序将从字符串的左列中打印值。
This is what I have so far: 这是我到目前为止的内容:
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
The output is: 输出为:
["D"]
I'm still in the process of figuring it out, but I do know that I need a while loop and possibly a for loop. 我仍在寻找答案的过程中,但我确实知道我需要一个while循环,可能还需要一个for循环。 I know the break will make the program end right after it gets its value;
我知道中断将使程序在获得其值后立即结束; I put it there because the program would just keep on going.
我把它放在那儿是因为程序会一直继续下去。 But besides that I'm totally stumped.
但是除此之外,我完全陷入了困境。
When you call list(str)
you split the string into individual characters. 当您调用
list(str)
您将字符串拆分为单个字符。 This happens because strings are sequences too. 这是因为字符串也是序列。
To split a string into separate lines use the str.splitlines()
method : 要将字符串拆分为单独的行,请使用
str.splitlines()
方法 :
for line in somestring.splitlines():
print line[0] # print first character
To print the first word of each line, use str.split()
to spilt on whitespace: 要打印每行的第一个单词 ,请使用
str.split()
溢出到str.split()
:
for line in somestring.splitlines():
print line.split()[0] # print first word
Or a little more efficiently by splitting only once: 或通过仅拆分一次来提高效率:
for line in somestring.splitlines():
print line.split(None, 1)[0] # print first word
This is easier: 这比较容易:
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...
or: 要么:
print('\n'.join(e[0] for e in st.splitlines())) # first letter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.