목록의 문자열 항목을 단일 문자열로 연결하는 더 간단한 방법이 있습니까? str.join()
기능을 사용할 수 있습니까 ?
예를 들어 이것은 입력 ['this','is','a','sentence']
이며 원하는 출력입니다this-is-a-sentence
sentence = ['this','is','a','sentence']
sent_str = ""
for i in sentence:
sent_str += str(i) + "-"
sent_str = sent_str[:-1]
print sent_str
답변
사용 join
:
>>> sentence = ['this','is','a','sentence']
>>> '-'.join(sentence)
'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이 string 메소드 인 이유 를 초보자가 아는 것이 매우 유용합니다
.
처음에는 매우 이상하지만 이후에는 매우 유용합니다.
결합 결과는 항상 문자열이지만 결합 할 오브젝트는 여러 유형 (제너레이터, 목록, 튜플 등) 일 수 있습니다.
.join
메모리를 한 번만 할당하기 때문에 더 빠릅니다. 기존 연결보다 낫습니다 ( 확장 된 설명 참조 ).
일단 배우면 매우 편안하며 괄호를 추가하기 위해 이와 같은 트릭을 수행 할 수 있습니다.
>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'
>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'
답변
하지만 @Burhan 칼리드의 대답은 좋다, 나는이 같은 더 이해할 수 있다고 생각 :
from str import join
sentence = ['this','is','a','sentence']
join(sentence, "-")
join ()의 두 번째 인수는 선택 사항이며 기본값은 “”입니다.
편집 :이 함수는 파이썬 3에서 제거되었습니다
답변
문자열을 결합하는 방법을 지정할 수 있습니다. ‘-‘대신 ”
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
답변
우리는 또한 파이썬을 사용할 수 있습니다 reduce 함수를 :
from functools import reduce
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
답변
def eggs(someParameter):
del spam[3]
someParameter.insert(3, ' and cats.')
spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
