문자열 <-> 배열 변환

Hyun·2023년 6월 18일
0

파이썬

목록 보기
5/17
post-thumbnail

배열 -> 문자열

배열의 요소들이 문자들로만 이루어져있는지, 숫자가 포함되어 있는지에 따라 아주 약간 다르다.

join()

요소들을 문자열로 합치는데 요소들 사이에 char문자를 넣어준다.

  • 배열의 요소들이 문자로만 이루어져 있는 경우
    : char.join(s for s in 배열이름)

ex)

arr = ["a", "b", "c", "d", "e"]
result = ' '.join(s for s in arr)
print(result) # a b c d e
  • 배열의 요소에 숫자가 포함되어 있는 경우(숫자만 있는 경우도 포함)
    : char.join(str(s) for s in 배열이름)

ex)

arr = [1, "a", "2", "b", "3"]
result = ' '.join(str(s) for s in arr)
print(result) # 1 a 2 b 3

arr = [1, 2, 3, 4, 5]
result = ' '.join(str(s) for s in arr)
print(result) # 1 2 3 4 5

문자열 -> 배열

split()

문자열을 특정 구분자로 구분하여 문자열을 나누어 배열을 만들어 반환한다.
방법: 배열이름.split('구분자')

ex)

str1 = "app bomb good"
str2 = "appbombgood"

result3 = str1.split(' ')
print(result3) # ['app', 'bomb', 'good']
result4 = str2.split(' ')
print(result4) # ['appbombgood']

list()

단일 문자로 구분된 배열을 만들어 반환한다.(단일 문자에 공백도 포함)
방법: list(배열이름)

ex)

str1 = "app bomb good"
str2 = "appbombgood"

result1 = list(str1)
print(result1) # ['a', 'p', 'p', ' ', 'b', 'o', 'm', 'b', ' ', 'g', 'o', 'o', 'd']
result2 = list(str2)
print(result2) # ['a', 'p', 'p', 'b', 'o', 'm', 'b', 'g', 'o', 'o', 'd']
profile
better than yesterday

0개의 댓글