목록의 항목을 단일 문자열에 연결하는 방법
문자열 목록을 단일 문자열로 연결하려면 어떻게 해야 합니까?
예를 들어,['this', 'is', 'a', 'sentence'], 입수방법"this-is-a-sentence"?
개별 변수에서 몇 개의 문자열을 처리하는 방법은 Python에서 문자열을 다른 문자열에 추가하는 방법을 참조하십시오.
반대로 문자열에서 목록 작성은 문자열을 문자 목록으로 분할하는 방법을 참조하십시오.또는 문자열을 단어 목록으로 분할하려면 어떻게 해야 합니까?
사용방법:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
리스트를 문자열로 변환하는 보다 일반적인 방법(숫자 목록도 포함)은 다음과 같습니다.
>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
12345678910
조인(join)이 왜 현악기인지 초보자에게 매우 유용합니다.
처음에는 매우 이상하지만, 이후에는 매우 유용합니다.
조인 결과는 항상 문자열이지만 조인되는 개체는 여러 유형(제너레이터, 목록, 튜플 등)일 수 있습니다.
.join메모리를 한 번만 할당하기 때문에 더 빠릅니다.기존 연결보다 우수합니다(확장 설명 참조).
일단 배우면 굉장히 편하고 이런 묘기를 해서 괄호를 붙일 수 있어요.
>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'
>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'
미래에서 편집: 아래 답변을 사용하지 마십시오.이 함수는 Python 3에서 제거되었으며 Python 2는 중지되었습니다.Python 2를 사용하고 있는 경우에도 Python 3 ready code를 작성하여 업그레이드를 용이하게 해야 합니다.
@Burhan Khalid의 답변은 좋지만, 저는 이렇게 하는 것이 더 이해할 수 있다고 생각합니다.
from str import join
sentence = ['this','is','a','sentence']
join(sentence, "-")
join()의 두 번째 인수는 옵션이며 기본값은 " " 입니다.
list_abc = ['aaa', 'bbb', 'ccc']
string = ''.join(list_abc)
print(string)
>>> aaabbbccc
string = ','.join(list_abc)
print(string)
>>> aaa,bbb,ccc
string = '-'.join(list_abc)
print(string)
>>> aaa-bbb-ccc
string = '\n'.join(list_abc)
print(string)
>>> aaa
>>> bbb
>>> ccc
Python을 사용할 수도 있습니다.reduce기능:
from functools import reduce
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
스트링의 결합 방법을 지정할 수 있습니다.대신'-', 를 사용할 수 있습니다.' ':
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
혼재된 콘텐츠목록을 문자열화하는 방법은 다음과 같습니다.
다음 목록을 고려하십시오.
>>> aa
[None, 10, 'hello']
문자열로 변환:
>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'
필요한 경우 목록으로 다시 변환합니다.
>>> ast.literal_eval(st)
[None, 10, 'hello']
최종적으로 콤마로 구분된 문자열을 생성할 경우 다음과 같이 사용할 수 있습니다.
sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"
def eggs(someParameter):
del spam[3]
someParameter.insert(3, ' and cats.')
spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
.join() 메서드를 사용하지 않으면 다음 메서드를 사용할 수 있습니다.
my_list=["this","is","a","sentence"]
concenated_string=""
for string in range(len(my_list)):
if string == len(my_list)-1:
concenated_string+=my_list[string]
else:
concenated_string+=f'{my_list[string]}-'
print([concenated_string])
>>> ['this-is-a-sentence']
따라서 이 예에서는 python이 목록의 마지막 단어에 도달했을 때 python은 concenated_string에 "-"를 추가해서는 안 됩니다.문자열의 마지막 단어가 아닌 경우 항상 "-" 문자열을 concenated_string 변수에 추가합니다.
언급URL : https://stackoverflow.com/questions/12453580/how-to-concatenate-join-items-in-a-list-to-a-single-string
'programing' 카테고리의 다른 글
| 본문을 브라우저 높이의 100%로 만듭니다. (0) | 2023.04.09 |
|---|---|
| dispatch_async에 대해서 (0) | 2023.04.09 |
| Git - 메서드/함수의 변경 이력은 어떻게 표시합니까? (0) | 2023.04.09 |
| 문자열에서 슬래시 발생 횟수를 찾는 방법 (0) | 2023.04.09 |
| 커스텀 컨트롤과 사용자 컨트롤 (0) | 2023.04.09 |