Prepare > Python > Strings > String Split and Join

2023. 6. 29. 21:13HackerRank-Python

https://www.hackerrank.com/challenges/python-string-split-and-join/problem?isFullScreen=true

 

String Split and Join | HackerRank

Use Python's split and join methods on the input string.

www.hackerrank.com

 

문제


You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.

 

코드


def split_and_join(line):
    # write your code here
    line = line.split(" ")
    return "-".join(line)

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

 

 

노트


split() 함수

a.split(sep="[구분자]", maxsplit=[분할횟수])
a.split("[구분자]", [분할횟수]) # 둘다 같은 식임

a.split("[구분자]") # 분할회수 최대: 나눌 수 있을 때 까지 나눔
# INPUT
a = "ha.ckrer.ran.k.com"
print(a)
print(a.split(".", 2))
  • 앞에서 부터 2번만 분할함
# OUTPUT
ha.ckrer.ran.k.com
['ha', 'ckrer', 'ran.k.com']
  • string -> list

 

 

join() 함수

"[구분자]"a.join([리스트]) # 구분자에 공백 가능

 

# INPUT
b = ["hacker", "rank", "dot", "com"]
print(b)
print("-".join(b))
  • 리스트의 각 값을 구분자(-)로 연결함
# OUTPUT
['hacker', 'rank', 'dot', 'com']
hacker-rank-dot-com
  • list -> string