본문 바로가기

Python

[Python] 모음 제거, .replace(), .join(), 리스트 컴프리헨션

문제 설명

영어에선 a, e, i, o, u 다섯 가지 알파벳을 모음으로 분류합니다. 문자열 my_string이 매개변수로 주어질 때 모음을 제거한 문자열을 return하도록 solution 함수를 완성해주세요.

 

.replace(old_value, new_value, count)

  • The replace() method replaces a specified phrase with another specified phrase.
    지정된 구문을 다른 구문으로 대체
  • Parameter Description
oldvalue Required. The string to search for
newvalue Required. The string to replace the old value with
count Optional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences
반복 횟수

count option 적용 화면(one -> three로 2번만 변경)

 

W3Schools.com

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

def solution(my_string):
    vowelList = ['a', 'e', 'i', 'o', 'u']
    for vowel in vowelList:
        my_string = my_string.replace(vowel, '')
    return my_string

 

.join(), 리스트 컴프리헨션 

  • 컴프리헨션 문법
    • 조건:
      [x for x in range(1, 10+1) if x % 2 == 0]
      [ x for x in range(10) if x < 5 if x % 2 == 0 ]
    • 반복: [ (x, y) for in ['쌈밥', '치킨', '피자'] for in ['사과', '아이스크림', '커피']]
# 기존 문법
numbers = []
for n in range(1, 10+1):
	numbers.append(n)

# 컴프리헨션
[x for x in range(10)]

 

def solution(my_string):
    vowels = 'aeiou'
    return ''.join(char for char in my_string if char not in vowels)
  • .join()
    • ''.join(): 띄어쓰기 없이 조인
  • 리스트 컴프리헨션
    • for문: for char in my_string
    • if문: if char not in vowels
    • join 함수: ''.join(char)

 

반응형