파이썬으로 문자열 다루기 2/2

파이썬으로 문자열 다루기 2/2


파이썬으로 문자열을 다루는 간단한 방법을 이전에 알아보았습니다. 이번에는 파이썬에서 제공하는 문자열 관련 함수들에 대해서 알아보도록 하겠습니다.




upper()


문자열을 대문자로 변경하기


lower()


문자열을 소문자로 변경하기


isupper()


문자열이 대문자로만 이루어 졌는가?


islower()


문자열이 소문자로만 이루어 졌는가?


위의 함수에 대해서 조금씩 알아보도록 하겠습니다.


print(“”” “abcdef” in “ABCDEFGHI” “””)

print(“abcdef” in “ABCDEFGHI”)


print(“”” “abcdef”.upper() in “ABCDEFGHI” “””)

print(“abcdef”.upper() in “ABCDEFGHI”)


print(“”” “abcdef” in “ABCDEFGHI”.lower() “””)

print(“abcdef” in “ABCDEFGHI”.lower())



print(“”” “abcdef”.isupper() “””)

print(“abcdef”.isupper())


print(“”” “abcDef”.isupper() “””)

print(“abcDef”.isupper())


print(“”” “ABCDEFGHI”.isupper() “””)

print(“ABCDEFGHI”.isupper())



print(“”” “ABCDEFGHI”.islower() “””)

print(“ABCDEFGHI”.islower())



print(“”” “ABCDEFGHi”.islower() “””)

print(“ABCDEFGHi”.islower())


print(“”” “abcdef”.islower() “””)

print(“abcdef”.islower())


위의 코드를 실행하면 아래와 같은 결과를 확인할 수 있습니다.




두번째로 알아볼 함수들은 다음과 같습니다.


isalpha()


문자열이 문자로만 구성되어있으며 빈칸이 없으면 참


isalnum()


문자열이 문자와 숫자로만 구성되어 있으며 빈칸이 없으면 참


isdecimal()


문자열이 숫자로만 구성되어있으며 빈칸이 없으면 참


isspace()


문자열이 빈칸, 공백, 탭, 줄바꿈 문자로만 구성되어 있지만 비어 있지 않으면 참


istitle()


문자열이 단어들로만 구성되어 있으며 각 단어는 대문자로 시작하고 그 뒤에 따라오는 글자들은 소문자로 되어 있으면 참


아래 코드는 몇가지 함수에 대한 예제입니다.


print(“”” “hello world!”.isalpha() “””)

print(“hello world!”.isalpha())


print(“”” “hello world”.isalpha() “””)

print(“hello world”.isalpha())


print(“”” “helloworld”.isalpha() “””)

print(“helloworld”.isalpha())


print(“”” “helloworld123”.isalpha() “””)

print(“helloworld123”.isalpha())


print(“”” “helloworld123”.isalnum() “””)

print(“helloworld123”.isalnum())


print(“”” “123”.isdecimal() “””)

print(“123”.isdecimal())


print(“”” ”   “.isspace() “””)

print(”   “.isspace())



print(“”” “This Is Title”.istitle() “””)

print(“This Is Title”.istitle())


print(“”” “This Is Title 123”.istitle() “””)

print(“This Is Title 123”.istitle())


print(“”” “This Is not Title”.istitle() “””)

print(“This Is not Title”.istitle())



위의 예제와 결과를 확인하고 어디에서 문자열을 사용할지에 대해서 고민해 보기 바랍니다.




다음으로 알아볼 메소드는


startwith()


메게변수로 전달된 문자열로 문장이 시작하면 참


endswith()


매게변수로 전달된 문자열로 끝나면 참



아래의 코드를 실행해보도록 하겠습니다.



print(“”” “http://google.com”.startwith(“http”) “””)

print(“http://google.com”.startwith(“http”))



print(“”” “http://google.com”.endswith(“.com”) “””)

print(“http://google.com”.endswith(“.com”))




코드를 실행하면 위와같은 결과를 얻을수 있습니다. 주소가 https인지 http인지 알아보는 방법에 대해서 간단하게 코딩하면 아래와 같을수 있겠죠.



def get_protocol(url) :

    if url.startswith(“http:”) :

        return “http”

    elif url.startswith(“https:”) :

        return “https”

    else:       

        return “others”

   

   

   

print(“”” get_protocol(“http://google.com”) “””)

print(get_protocol(“http://google.com”))


print(“”” print(get_protocol(“http://google.com”)) “””)

print(get_protocol(“http://google.com”))


print(“”” print(get_protocol(“test@mail.com”)) “””)

print(get_protocol(“test@mail.com”))



위의 코드를 실행하면 아래와 같이 프로토콜의 종류를 알수 있습니다.



이번에 알아볼 함수는 문자열을 자르고 합치는 함수입니다.


split()


매게변수로 넘겨진 문자로 문자열을 나누어서 리스트로 리턴합니다.


join()


리스트를 특정한 문자열로 합쳐줍니다.



문자열을 나누고 합치는 좋은 함수 입니다.


print(“”” “http://w3devlabs.net/wp”.split(“/”) “””)

print(“http://w3devlabs.net/wp”.split(“/”))


print(“”” “a b c d e fff”.split() “””)

print(“a b c d e fff”.split())



print(“”” “http://w3devlabs.net/wp”.split(“/”).join(“^”) “””)

print(“^”.join(“http://w3devlabs.net/wp”.split(“/”)))




쓰임세를 잘 보면 첫번째는 문자를 줘서 해당 문자로 나누었습니다. 그런데 두번재는 매게변수가 없습니다. 매게변수가 없는경우 공백, 탭, 줄바꿈과 같은 공백 문자가 있는 곳에서 분리됩니다.



마지막 세번째는 특정 문자열로 나누고 특정 문자열로 합쳤습니다. replace함수와 동일한 역할을 하고 있습니다. 실제 다른 언어에서는  긴 문자열의 경우 replace보다 split > join으로 하는 경우가 더 빠른 경우도 있다고 합니다.



이번에 알아볼 문자열 함수는


rjust()


ljust()


center()


각각의 함수는 호출한 문자열을 왼쪽 또는 오른쪽 , 센터에 위치시키고 있습니다.


코드를 만들어서 실행해보도록 하겠습니다.


print(“”” “test”.rjust(30) “””)

print(“test”.rjust(30))


print(“”” “test”.ljust(30) “””)

print(“test”.ljust(30))


print(“”” “test”.center(30) “””)

print(“test”.center(30))




코드를 실행하면 위와 같은 결과를 얻을수 있습니다.


프로그램을 배우면서 가장 좋은 방법은 해당 함수를 사용하면서 어떻게 사용이 되는지 확인하는 것입니다.


위의 실행결과를 보고 함수의 정확한 뜻을 유추해 내시기 바랍니다.



이번에 알아볼 함수는


strip()


문자열의 앞뒤 공백(빈칸, 탭, 줄바꿈)을 제거한다.


rstrip()


문자열의 뒤쪽 공백(빈칸, 탭, 줄바꿈)을 제거한다.


lstrip()


문자열의 앞쪽 공백(빈칸, 탭, 줄바꿈)을 제거한다.


어떻게 사용하는지 알아보도록 하겠습니다.


print(“”” ”   Hello world!!   “.strip() “””)

print(”   Hello world!!    “.strip())


print(“”” ”   Hello world!!   “.lstrip() “””)

print(”   Hello world!!    “.lstrip())


print(“”” ”   Hello world!!   “.rstrip() “””)

print(”   Hello world!!    “.rstrip())




세개의 함수를 이용해서 문자열에 어떻게 사용하는지 알아보았습니다.


위에서 문자열에 대한 다양한 함수를 알아보았습니다. 이러한 문자열 함수를 이용하지 않더라도 문자열을 조작하는데 문제 없지만 이러한 함수를 이용하여 좀더 효과적으로 문자열을 조작하고 프로그램을 안정화 시킬수 있습니다.


이상으로 문자열의 함수에 대해서 알아보았습니다.




댓글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.