IT

어디에 목록의 요소에서 후행 줄 바꿈 제거

lottoking 2020. 8. 4. 22:45
반응형

어디에 목록의 요소에서 후행 줄 바꿈 제거


나는 다음과 같은 형식으로 단어의 큰 목록을 가져와야합니다.

['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']

그런 다음 스트립 기능을 사용하여 다음과 같이 바꾸십시오.

['this', 'is', 'a', 'list', 'of', 'words']

내가 쓴 것이 효과가 생각했지만 오류가 계속 발생합니다.

" 'list'개체에 'strip'속성이 없습니다."

내가 시도한 코드는 다음과 유연합니다.

strip_list = []
for lengths in range(1,20):
    strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
    strip_list.append(lines[a].strip())

>>> my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> map(str.strip, my_list)
['this', 'is', 'a', 'list', 'of', 'words']

목록 이해력? [x.strip() for x in lst]


당신은 목록 이해 를 사용할 수 있습니다 :

strip_list = [item.strip() for item in lines]

또는 기능 :map

# with a lambda
strip_list = map(lambda it: it.strip(), lines)

# without a lambda
strip_list = map(str.strip, lines)


이는 PEP 202에 정의 된 목록 이해를 사용하여 수행 할 수 있습니다.

[w.strip() for w in  ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']]

다른 모든 답변과 주로 목록 이해력에 관한 것입니다. 그러나 오류를 설명하기 위해 :

strip_list = []
for lengths in range(1,20):
    strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
    strip_list.append(lines[a].strip())

a색인이 아닌 목록의 회원입니다. 당신이 쓸 수있는 것은 이것입니다.

[...]
for a in lines:
    strip_list.append(a.strip())

또 다른 중요한 의견 : 다음과 같이 빈 목록을 만들 수 있습니다.

strip_list = [0] * 20

그러나 이것은 당신의 목록 .append 물건을 추가 하기 때문에 그렇게 유용하지 않습니다 . 귀하의 경우에는 제거 된 문자열을 추가 할 때 항목별로 항목을 작성하므로 기본 값으로 목록을 만드는 것은 유용하지 않습니다.

따라서 코드는 다음과 같아야합니다.

strip_list = []
for a in lines:
    strip_list.append(a.strip())

그러나 확실히 가장 좋은 것은 이것입니다. 이것은 정확히 똑같은 것입니다.

stripped = [line.strip() for line in lines]

단순한 것보다 더 복잡한 것이 있다면 .strip이것을 함수에 넣고 똑같이하십시오. 이것이 목록 작업에 가장 읽기 쉬운 방법입니다.


후행 공백 만 제거해야하는 경우를 사용할 수 있습니다 str.rstrip(). 이는 다음보다 약간 더 효율적입니다 str.strip().

>>> lst = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> [x.rstrip() for x in lst]
['this', 'is', 'a', 'list', 'of', 'words']
>>> list(map(str.rstrip, lst))
['this', 'is', 'a', 'list', 'of', 'words']

참고 URL : https://stackoverflow.com/questions/7984169/remove-trailing-newline-from-the-elements-of-a-string-list

반응형