본문으로 바로가기

HackerRank Python Solution / sWAP cASE

category Develop/hackerrank.com 2022. 1. 11. 23:58

 

 

sWAP cASE

def swap_case(sentence):
    updated_s = ""
    for c in sentence:
        if c.isupper():
            updated_s += c.lower()
        elif c.islower():
            updated_s += c.upper()
        else:
            updated_s += c
    return updated_s


if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

문장의 대문자를 소문자로, 소문자를 대문자로, 문자가 아닌 글자(character)는 그대로 반환하는 코드이다.

 

 

해설

연산자("+="), if문,  문자열 관련 함수를 사용하여 문장을 반환한다.  

 

큰따옴표 ""

>>> print("aBc")
aBc

문자열을 만들기 위한 도구이다. 



for문

>>> a = "aBc"
>>> for c in s:
...     print(s)
...
aBc
aBc
aBc

for함수는 반복문이다. 예를들어 입력되는(in) s의 문자길이가 3칸("aBc")이라면 3번 돌려준다.

if문

https://bohemihan.tistory.com/entry/HackerRank-Python-Solution-If-Else

 

HackerRank Python Solution / If-Else

Problem- 2 Given an integer, n, perform the following conditional actions: If n is odd, print Weird If n is even and in the inclusive range of 2 to 5, print Not Weird If n is even and in the inclus..

bohemihan.tistory.com

 

isupper / islower

# 사용법
>>> 문자열.isupper():

>>> 문자열 = "aBc"
>>> 문자열.isupper()
False

>>> 문자열 = "aBc"
>>> 문자열.islower()
False

>>> 문자열 = "abc"
>>> 문자열.isupper()
False

>>> 문자열 = "abc"
>>> 문자열.islower()
True

대문자/소문자를 판별하는 함수

 

upper() / lower()

# 사용법

>>> 문자열.upper():
... 

>>> 문자열 = "aBc"
>>> 문자열.upper()
'ABC'

>>> 문자열 = "aBc"
>>> 문자열.lower()
'abc'

문자열을 대문자/소문자로 변환하는 함수

 

파이썬 연산자 +=

# 연산자의 왼쪽값에 오른쪽값을 더하여 왼쪽값에 할당한다.
>>> x = 1 
>>> y = 2
>>> x + y = 3
3

>>> x = 1
>>> y = 2
>>> x += y
>>> print(x)
>>> print(y)
3
2