2013-07-13 3 views
0

문자열의 왼쪽 열에있는 값을 인쇄하는 프로그램을 작성하려고합니다.Python 3.x - 문자열의 왼쪽 열의 값을 얻는 방법

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

'진정한 동안'더 간결 것이며 지점에 .. –

+0

변수'str'의 이름을 지정하지 마십시오 기본 제공 유형을 가린다. –

답변

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 
+0

우수. : 3 splitlines() 메서드 없이는 어떻게 해야할지 궁금한가요? 나는 그 방법이 없다면 어떤 종류의 미친 슈퍼 둥지가 있어야한다고 가정합니다. –

+0

그 다음 무엇을하려고합니까? '.splitlines()'를 사용하는 대신에리스트 내장과/또는'\ n' 문자로 나눌 수 있지만 어떤 종류의 루프에 대한 필요성은 바꾸지 않습니다. –

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 
관련 문제