파이썬에서리스트를 문자열로 변환하는 방법
파이썬에서 str 리스트를 문자열로 변환
str.join()메소드를 사용하여 str 데이터 타입 요소가있는리스트를 문자열로 변환 할 수 있습니다.
예를 들어
A = ["a", "b", "c"]
StrA = "".join(A)
print(StrA)
## StrA is "abc"
join 메소드는 임의의 수의 문자열을 연결하며, 메소드가 호출 된 문자열은 주어진 각 문자열 사이에 삽입됩니다. 예제에서 볼 수 있듯이 빈 문자열 인 문자열 ""은 목록 요소 사이에 삽입됩니다.
요소 사이에 공백을 추가하려면 다음을 사용해야합니다.
StrA = " ".join(A)
## StrA is "a b c"
파이썬에서 비 str 목록을 문자열로 변환
join 메소드에는 주어진 매개 변수로 str 데이터 유형이 필요합니다. 따라서 int형식 목록에 가입하려고하면 TypeError 가 표시됩니다.
>>> a = [1,2,3]
>>> "".join(a)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
"".join(a)
TypeError: sequence item 0: expected str instance, int found
int 타입은 결합되기 전에 str 타입으로 변환되어야합니다.
리스트 내포
>>> a = [1,2,3]
>>> "".join([str(_) for _ in a])
"123"
map 기능
>>> a = [1,2,3]
>>> "".join(map(str, a))
'123'
map 함수는 str 함수를 목록 a 의 모든 항목에 적용하고 반복 가능한 map 객체를 반환합니다.
"".join()은 map 객체의 모든 요소를 반복하고 연결된 요소를 문자열로 반환합니다.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook관련 문장 - Python String
- Python의 문자열에서 쉼표 제거
- 파이썬 방식으로 문자열이 비어 있는지 확인하는 방법
- Python에서 문자열을 변수 이름으로 변환
- 파이썬에서 문자열에서 공백을 제거하는 방법
- Python의 문자열에서 숫자 추출
- 파이썬에서 문자열을 날짜 / 시간으로 변환하는 방법
