Python_Matter/Solve

Python Learn the basics Quiz 44

AnKiWoong 2019. 6. 10. 11:48
반응형

Q>

You are given a string and two markers (the initial and final). You have to find a substring enclosed between these two markers. But there are a few important conditions:

(문자열과 두 개의 마커 (초기 및 최종)가 주어집니다. 이 두 마커 사이에있는 부분 문자열을 찾아야합니다. 그러나 몇 가지 중요한 조건이 있습니다.)

  • The initial and final markers are always different.(초기 및 최종 마커는 항상 다름)
  • If there is no initial marker, then the first character should be considered the beginning of a string.(초기 마커가 없으면 첫 번째 문자를 문자열의 시작으로 간주)
  • If there is no final marker, then the last character should be considered the ending of a string.(최종 마커가 없으면 마지막 문자는 문자열의 끝으로 간주)
  • If the initial and final markers are missing then simply return the whole string.(초기 및 최종 마커가 누락 된 경우 전체 문자열을 반환)
  • If the final marker comes before the initial marker, then return an empty string.(마지막 마커가 초기 마커 앞에 오는 경우 빈 문자열을 반환)

 

Input: Three arguments. All of them are strings. The second and third arguments are the initial and final markers.

(세 가지 인수. 모두 문자열입니다. 두 번째 및 세 번째 인수는 초기 및 최종 마커입니다.)

 

Output: A string.

(문자열.)

 

Example:

between_markers('What is >apple<', '>', '<') == 'apple'
between_markers('No[/b] hi', '[b]', '[/b]') == 'No'

 

How it is used: for parsing texts

(텍스트를 파싱하는 데 사용됩니다.)

 

Precondition: can't be more than one final marker and can't be more than one initial

(하나 이상의 최종 마커가 될 수 없으며 하나 이상의 초기 마커가 될 수 없습니다.)

 

A>

def between_markers(text: str, begin: str, end: str) -> str:
    """
        returns substring between two given markers
    """
    # your code here
    # 시작 마커 위치 찾기
    if begin in text:
        # 마커의 시작 인덱스 + 마커의 길이
        begin_index = text.find(begin) + len(begin)
    # 마커가 없으면 0
    else:
        begin_index = 0

    if end in text:
        end_index = text.find(end)
    else:
        end_index = len(text)

    # 슬라이싱
    return text[begin_index:end_index]


if __name__ == '__main__':
    print('Example:')
    print(between_markers('What is >apple<', '>', '<'))

    # These "asserts" are used for self-checking and not for testing
    assert between_markers('What is >apple<', '>', '<') == "apple", "One sym"
    assert between_markers("<head><title>My new site</title></head>",
                           "<title>", "</title>") == "My new site", "HTML"
    assert between_markers('No[/b] hi', '[b]', '[/b]') == 'No', 'No opened'
    assert between_markers('No [b]hi', '[b]', '[/b]') == 'hi', 'No close'
    assert between_markers('No hi', '[b]', '[/b]') == 'No hi', 'No markers at all'
    assert between_markers('No <hi>', '>', '<') == '', 'Wrong direction'
    print('Wow, you are doing pretty good. Time to check it!')

 

O>

Example:
apple
Wow, you are doing pretty good. Time to check it!

Process finished with exit code 0

 

S>

https://py.checkio.org

반응형