티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Why is it string.join(list) instead of list.join(string)?
list.join(string)이 아닌 string.join(list)인 이유는 무엇인가요?
문제 내용
This has always confused me. It seems like this would be nicer:
이것은 항상 저를 혼란스럽게 했습니다. 이것이 더 좋을 것 같습니다:
["Hello", "world"].join("-")
Than this:
이것보다:
"-".join(["Hello", "world"])
Is there a specific reason it is like this?
이런 특별한 이유가 있나요?
높은 점수를 받은 Solution
It's because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the "joiner" must be strings.
어떤 iterable도 조인될 수 있지만(예: list, tuple, dict, set) 그 내용과 "joiner"는 문자열이어야 하기 때문입니다.
For example:
예:
'_'.join(['welcome', 'to', 'stack', 'overflow'])
'_'.join(('welcome', 'to', 'stack', 'overflow'))
'welcome_to_stack_overflow'
Using something other than strings will raise the following error:
문자열이 아닌 다른 문자열을 사용하면 다음 오류가 발생합니다.
TypeError: sequence item 0: expected str instance, int found
가장 최근 달린 Solution
-
in "-".join(my_list)
declares that you are converting to a string from joining elements a list.It's result-oriented. (just for easy memory and understanding)
-"-".join(my_list)에서 아이템을 리스트에 결합하여 문자열로 변환한다고 선언합니다. 그것은 결과 지향적입니다. (쉽게 기억하고 이해하기 위해)
I made an exhaustive cheatsheet of methods_of_string for your reference.
저는 당신이 참고할 수 있도록 methods_of_string의 전체 치트 시트를 만들었습니다.
string_methods_44 = {
'convert': ['join','split', 'rsplit','splitlines', 'partition', 'rpartition'],
'edit': ['replace', 'lstrip', 'rstrip', 'strip'],
'search': ['endswith', 'startswith', 'count', 'index', 'find','rindex', 'rfind',],
'condition': ['isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isnumeric','isidentifier',
'islower','istitle', 'isupper','isprintable', 'isspace', ],
'text': ['lower', 'upper', 'capitalize', 'title', 'swapcase',
'center', 'ljust', 'rjust', 'zfill', 'expandtabs','casefold'],
'encode': ['translate', 'maketrans', 'encode'],
'format': ['format', 'format_map']}
출처 : https://stackoverflow.com/questions/493819/why-is-it-string-joinlist-instead-of-list-joinstring
'개발 > 파이썬' 카테고리의 다른 글
딕셔너리에서 값으로 키 가져오기 (0) | 2022.12.11 |
---|---|
리스트 반대로 순회하기 (0) | 2022.12.11 |
딕셔너리 매핑 반전(키<->값)하기 (0) | 2022.12.11 |
리스트에서 동일 아이템 개수 구하기 (0) | 2022.12.11 |
현재 실행 중인 파일의 경로와 이름 가져오기 (0) | 2022.12.10 |