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
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
'Develop > hackerrank.com' 카테고리의 다른 글
HackerRank Python Solution / What's Your Name? (0) | 2022.01.17 |
---|---|
HackerRank Python Solution / String Split and Join (0) | 2022.01.17 |
HackerRank Python Solution / Tuples (0) | 2022.01.11 |
HackerRank Python Solution / Lists (0) | 2022.01.10 |
HackerRank Python Solution / Finding the percentage (0) | 2022.01.07 |