티스토리 뷰

반응형

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

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

 

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

How would you make a comma-separated string from a list of strings?

리스트 문자열을 쉼표로 구분된 문자열로 만드는 방법은 무엇인가요?

 문제 내용 

What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c'] to 'a,b,c'? (The cases ['s'] and [] should be mapped to 's' and '', respectively.)

연속된 두 개의 문자열 사이에 쉼표가 추가되도록 문자열 시퀀스를 연결하는 방법은 무엇인가요? 예를 들어, ['a', 'b', 'c']를 'a,b,c'로 변환하는 방법은 무엇인가요? (['s']와 [] 경우 각각 's'와 ''로 변환되어야 함)

 

I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1], but also feeling somewhat unsatisfied.

보통 제가 사용하는 방법은 ''.join(map(lambda x: x+',',l))[:-1]같은데, 이 방법이 조금 불만족스러워요.

 

 

 

 높은 점수를 받은 Solution 

my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
'a,b,c,d'

This won't work if the list contains integers

하지만, 이 방법은 정수가 포함된 리스트에는 작동하지 않아요.

 


 

And if the list contains non-string types (such as integers, floats, bools, None) then do:

리스트에 정수, 부동소수점, 부울, None과 같은 문자열이 아닌 값이 포함되어 있는 경우 다음과 같이 하세요:
my_string = ','.join(map(str, my_list)) 

 

 

 가장 최근 달린 Solution 

If you want to do the shortcut way :) :

만약 단축 방법을 원한다면 :) :
','.join([str(word) for word in wordList])

 

But if you want to show off with logic :) :

하지만, 논리적인 방법을 자랑하고 싶다면 :) :
wordList = ['USD', 'EUR', 'JPY', 'NZD', 'CHF', 'CAD']
stringText = ''

for word in wordList:
    stringText += word + ','

stringText = stringText[:-2]   # get rid of last comma
print(stringText)

 

 

출처 : https://stackoverflow.com/questions/44778/how-would-you-make-a-comma-separated-string-from-a-list-of-strings

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