簡體   English   中英

Python 3.x-如何獲取字符串左列的值

[英]Python 3.x - how do get the values of the left column of a string

我正在嘗試編寫一個程序,該程序將從字符串的左列中打印值。

這是我到目前為止的內容:

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循環。 我知道中斷將使程序在獲得其值后立即結束; 我把它放在那兒是因為程序會一直繼續下去。 但是除此之外,我完全陷入了困境。

當您調用list(str)您將字符串拆分為單個字符。 這是因為字符串也是序列。

要將字符串拆分為單獨的行,請使用str.splitlines()方法

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

要打印每行的第一個單詞 ,請使用str.split()溢出到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

這比較容易:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM