눈송이의 개발생활
[Python]String 관련 함수 - join, reversed 본문
List를 String으로 바꾸는 방법
📌 join 함수
리스트에 있는 모든 요소를 합쳐서 하나의 문자열로 바꿔주는 함수
'구분자'.join(list)
list = ['a', 'b', 'c', 'd']
print(''.join(list))
# abcd
print(' '.join(list))
# a b c d
print(','.join(list))
# a,b,c,d
리스트 안의 모든 요소가 string형이 아니면 error가 발생하기 때문에 형변환을 해준 뒤에 join 함수를 사용하면 예외처리 할 수 있다.
list = ['a', 'b', 1, 2]
print(' '.join(str(e) for e in list))
# a b 1 2
📌 for문 사용
list = ['a', 'b', 'c', 'd']
str = ''
for s in list:
str += s
print(str)
# abcd
문자열 뒤집기 (Reverse String)
📌 문자열 반대로 잘라서 입력하고 출력하기
s = 'i am happy today'
s = s[::-1]
print(s)
# yadot yppah ma i
📌 reversed() 함수
s = 'i am happy today'
new_s = reversed(s)
print(new_s)
# <reversed object at 0x000001FFFF099A00>
print(''.join(new_s))
# yadot yppah ma i
reversed()는 'reversed'객체를 반환
내장함수이고 print를 하면 속성값을 반환 → print(new_s)
원하는 자료형에 따라 형변환을 하고 출력하면 된다
l = ['a', 'b', 'c']
t = ('a', 'b', 'c')
list_1 = list(reversed(l))
tuple_1 = tuple(reversed(t))
print(list_1)
# ['c', 'b', 'a']
print(tuple_1)
# ('c', 'b', 'a')
'Programming Languages > Python' 카테고리의 다른 글
[Python]내장 함수 - zip() (0) | 2022.03.05 |
---|---|
[Python]자료구조 - deque (0) | 2022.01.16 |
[Python]itertools - permutations, combinations (순열과 조합) (0) | 2022.01.15 |
Comments