본문으로 바로가기

 

 

String Split and Join

def split_and_join(line):
    return "-".join(line.split())

if __name__ == '__main__':
    line = input()
    result = split_and_join(line)
    print(result)

 

해설

>>> line = input()
this is a string   # this ia a string을 input하는 경우
>>> words = line.split()
>>> print(words)
['this', 'is', 'a', 'string']
>>> result = "-".join(words)
>>> print(result)
this-is-a-string

>>> "-".join(line.split())
this-is-a-string

문장의 띄어쓰기(공백)을 작대기(-)로 바꾸는 코드이다.

split

>>> 문자열 = 'abc def 12 3'
>>> 문자열.split()
['abc', 'def', '12', '3']

>>> 문자열2 = 'ab,c d,ef 1,2 3,'
>>> 문자열2.split(',')
['ab', 'c d', 'ef 1', '2 3', '']

split 함수는 문자열을 나눠주는 기능이 있다.
문자열.split()처럼 괄호 안이 공백인 경우 스페이스, 탭, 엔터 등을 기준으로 문자열을 나눠준다

사용방법
문자열.split(sep='구분자', maxsplit='구분횟수')

파라미터
· sep : 해당 구분자를 기준으로 분할
· maxsplit : 분할을 실행할 횟수 (*디폴트 값은 -1로 해당 문자열을 자를 수 있을때까지 실행)

 

join

>>> words = ['this', 'is', 'a', 'string']
>>> "-".join(words)
'this-is-a-string'

join함수는 객체(iterable) 내의 문자사이에 '삽입할것'을 넣어주는 기능을 한다.

사용방법
삽입할것.join(iterable) 

파라미터
· join 함수는 객체(iterable) 자리에 List, Tuple, Dictionary, Set 등을 받는다.