본문 바로가기

Python

[Python/level 0] 문자 반복 출력하기 - 120825, join()

문제 설명

문자열 my_string과 정수 n이 매개변수로 주어질 때, my_string에 들어있는 각 문자를 n만큼 반복한 문자열을 return 하도록 solution 함수를 완성해보세요.

 

join()

  • The join() method takes all items in an iterable and joins them into one string.
    반복 가능한 문자열을 가져와 하나의 문자열로 결합합니다.
  • A string must be specified as the separator.
    구분자를 지정해야 합니다.
  • string.join(iterable)
Parameter Description
iterable Required. Any iterable object where all the returned values are strings

 

code - 1

def solution(my_string, n):
    answer = ''
    for i in my_string:
        answer += (i*n)
    return answer
  • for문 → answer += (i*n)
    • my_string을 한 글자씩 i로 for문을 돌립니다.
    • answer에 i*n(i를 n만큼 반복)을 더합니다.
  • return answer
    • 위 과정을 통해 더해진 answer 문자열을 return 합니다.

 

code - 2

def solution(my_string, n):
    return ''.join(s*n for s in my_string)
  • ''.join(s*n for s in my_string)
    • my_string을 한 글자씩 s로 for문을 돌립니다.
    • s*n 즉 s를 n만큼 반복한 값을 반환합니다.
    • ''.join 위 값을 join 함수를 이용해 한 문자열로 만들어줍니다.

 

반응형