Posts 가운데글자 가져오기 [Python]
Post
Cancel

가운데글자 가져오기 [Python]

1. 가운데 글자 가져오기


URL : https://programmers.co.kr/learn/courses/30/lessons/12903

1.1문제설명

  • 단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다.


1.2 제한사항

  • s는 길이가 1 이상, 100이하인 스트링입니다


1.3 Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
import math
answer = ''

def solution(s):
    if len(s) % 2 == 0:
        answer = s[math.trunc(len(s)/2)-1:math.trunc(len(s)/2)+1]
        return answer
    if len(s) % 2 != 0:
        answer = s[math.trunc(len(s)/2)]
        return answer
    return answer
s = 'abcdefgh'
solution(s)
1
'de'
  • 문자열 s가 주어지면 s의 길이를 len으로 구한뒤 나누기 2를 하고 math의 trunc를 이용하여 내림으로 가운대 위치를 구한다.
  • 문자열 s가 짝수라면 -1, +1 를 하여 s의 가운데 2글자를 반환함
  • 문자열 s가 홀수라면 그대로 반환하여 가운데를 구함
This post is licensed under CC BY 4.0 by the author.