본문 바로가기
Python/Python Examples

[Python Examples] 문자열 거꾸로 출력하기: #for loop, #def, if statement

by Henry Cho 2023. 9. 25.
728x90

문자열 거꾸로 출력하기: #for loop, #def, if statement

포스트 난이도: HOO_Junior


# Exmple codes

이번 포스트에서는 문자열을 거꾸로 출력해 보는 파이썬 예제코드를 살펴보려고 한다. 한마디로 문자열로 저장되어 있는 문장을 반대 순서로 출력이 되도록 만들어주는 셈이다. 아마 거꾸로 출력되는 문자열 예제는 프로그래밍 수업에서 웬만하면 많이 다루다 보니 이미 많은 브로들이 알고 있을 수도 있다. 그래서 한 가지 더 추가해서 특정 문자열만 출력이 되도록 하는 조건을 추가해 보았다. 이게 무슨 소리냐면, "/0"이라는 문자가 입력이 되어 있다면 이후에 작성된 문자열이 있더라도 산출되는 결과에 적용되지 않는 것이다. 또한 이번 예제코드에서는 for loop, if statement와 함께 def 기능을 같이 사용해 보았다. 아래의 예제코드를 살펴보면서 각 기능들에 대해 익숙해질 수 있다.


def append_and_reverse(firststring, secondstring):
    # Initialize variables to store the result and lengths of the input strings
    result = []
    first_len = 0
    second_len = 0

    # Calculate the lengths of the input strings
    for char in firststring:
        if char == '\0':
            break
        first_len += 1
    for char in secondstring:
        if char == '\0':
            break
        second_len += 1

    # Append characters from the first string
    for i in range(first_len):
        result.append(firststring[i])

    # Append characters from the second string
    for i in range(second_len):
        result.append(secondstring[i])

    # Reverse the result
    result.reverse()

    # Convert the result list back to a string
    result_str = ''.join(result)

    return result_str

# Define the input character arrays
firststring = "HOO\0"
secondstring = " AI\0"

# Call the function to append and reverse the strings
output = append_and_reverse(firststring, secondstring)

# Print the result
print("HOOAI:",output)

Figure1. 예제코드 결과


위의 예제코드를 실행하면 Figure1과 같이 문자열이 거꾸로 출력이되는 결과를 얻을 수 있다. 여기서 앞서 이야기한 바와 같이 정해진 문자열만 출력이 되도록 하는 조건을 코드에 추가해 주었기 때문에 "\0"을 작성해주지 않거나, "\0" 이후에 문자열이 더 있다고 할지라도 출력이 되지 않는다. 아래의 두 번째 예제코드에서는 "오늘도 난 카카오 주식을 산다."라는 문자열을 firststring에 추가해 주었지만 위의 예제코드 결과와 동일하게 출력이 되는 걸 알 수 있다.


def append_and_reverse(firststring, secondstring):
    # Initialize variables to store the result and lengths of the input strings
    result = []
    first_len = 0
    second_len = 0

    # Calculate the lengths of the input strings
    for char in firststring:
        if char == '\0':
            break
        first_len += 1
    for char in secondstring:
        if char == '\0':
            break
        second_len += 1

    # Append characters from the first string
    for i in range(first_len):
        result.append(firststring[i])

    # Append characters from the second string
    for i in range(second_len):
        result.append(secondstring[i])

    # Reverse the result
    result.reverse()

    # Convert the result list back to a string
    result_str = ''.join(result)

    return result_str

# Define the input character arrays
firststring = "HOO\0 오늘도 난 카카오 주식을 산다."
secondstring = "AI\0"

# Call the function to append and reverse the strings
output = append_and_reverse(firststring, secondstring)

# Print the result
print("HOOAI:",output)

Figure2. 예제코드2 결과


여기서 "\0" 표시를 삭제하게 된다면 firststring 변수에 있는 모든 문자열이 secondstring과 함께 모두 출력되는 걸 확인할 수 있다. 아래의 세 번째 예제코드를 통해서 비교해 보도록 하자.


def append_and_reverse(firststring, secondstring):
    # Initialize variables to store the result and lengths of the input strings
    result = []
    first_len = 0
    second_len = 0

    # Calculate the lengths of the input strings
    for char in firststring:
        if char == '\0':
            break
        first_len += 1
    for char in secondstring:
        if char == '\0':
            break
        second_len += 1

    # Append characters from the first string
    for i in range(first_len):
        result.append(firststring[i])

    # Append characters from the second string
    for i in range(second_len):
        result.append(secondstring[i])

    # Reverse the result
    result.reverse()

    # Convert the result list back to a string
    result_str = ''.join(result)

    return result_str

# Define the input character arrays
firststring = "HOO 오늘도 난 카카오 주식을 산다."
secondstring = "AI\0"

# Call the function to append and reverse the strings
output = append_and_reverse(firststring, secondstring)

# Print the result
print("HOOAI:",output)

Figure3. 예제코드3 결과


# github link

https://github.com/WhoisHOO/HOOAI/blob/main/Python%20Examples/append%20and%20reverse%20the%20strings


 

728x90

댓글