티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How do I split a string into a list of characters?

문자열을 문자 리스트로 어떻게 분할하나요?

 문제 내용 

How do I split a string into a list of characters? str.split does not work.

문자열을 문자 리스트로 어떻게 분할하나요? str.split이 작동하지 않습니다.
"foobar"    →    ['f', 'o', 'o', 'b', 'a', 'r']

 

 

 높은 점수를 받은 Solution 

Use the list constructor:

리스트 생성자를 사용하세요.
>>> list("foobar")
['f', 'o', 'o', 'b', 'a', 'r']

 

list builds a new list using items obtained by iterating over the input iterable. A string is an iterable -- iterating over it yields a single character at each iteration step.

list 함수는 입력 가능한 iterable 객체의 각 항목을 반복하여 새로운 리스트를 구성합니다. 문자열은 iterable 객체입니다. 문자열에 대해 반복을 수행하면 각 단계에서 하나의 문자가 반환됩니다.

 

 

 

 가장 최근 달린 Solution 

To split a string s, the easiest way is to pass it to list(). So,

문자열 s를 나누는 가장 쉬운 방법은 list()에 넘겨주는 것입니다. 따라서,
s = 'abc'
s_l = list(s) #  s_l is now ['a', 'b', 'c']

 

You can also use a list comprehension, which works but is not as concise as the above:

위의 방법보다 간결하지 않지만 리스트 내포를 사용할 수도 있습니다.
s_l = [c for c in s]

 

There are other ways, as well, but these should suffice. Later, if you want to recombine them, a simple call to "".join(s_l) will return your list to all its former glory as a string...

다른 방법도 있지만, 이 방법들로도 충분합니다. 이후에 리스트를 다시 결합하려면, "".join(s_l)과 같이 간단한 호출을 통해 리스트를 문자열로 바꿀 수 있습니다...

 

 

 

출처 : https://stackoverflow.com/questions/4978787/how-do-i-split-a-string-into-a-list-of-characters

반응형
댓글
공지사항
최근에 올라온 글