지난번 포스팅에서는 파이썬의 자료 유형인 

 - 숫자(Number), 

 - 문자열(String), 

 - 리스트(List), 

 - 튜플(Tuple), 

 - 사전(Dictionary) 


중에서 먼저 숫자(Number)와 문자열(String)의 기본 사용법을 소개하였습니다. 


이번 포스팅에서는 지난 포스팅에 이어서 문자열에 특화되어 문자열 자료형을 다양하게 처리할 수 있는 함수인 문자열 메소드(String Methods) 에 대해서 알아보겠습니다. 


문자열 메소드를 숙지하고 있으면 동일한 목적의 문자열 전처리를 위해 직접 프로그래밍을 하는 것보다 문자열 메소드를 사용한 1~2줄의 코드면 해결되므로 업무 효율도 오르고, for loop 문을 쓰는 것보다 속도도 훨씬 빠릅니다. 


[참고]  메소드 (Method)


내장 함수(Built-in Function)와는 달리 문자열 자료형과 같이 특정 자료형이 가지고 있는 함수를 메소드(Method) 라고 합니다. 메소드는 객체 지향 프로그래밍의 기능에 대응하는 파이썬 용어입니다. 함수와 거의 동일한 의미이지만 메소드는 클래스의 멤버라는 점이 다릅니다. 



평소에 공부해놓고 '아, 문자열 메소드에 이런 기능이 있었지!' 정도는 기억해놓고 있어야 바로 찾아서 쓰기 쉽겠지요? 아래에 문자열 메소드들을 기능에 따라서 그룹핑을 해보았는데요, 저의 경우 len(), find(), lower(), upper(), lstrip(), rstrip(), split(), splitlines(), replace(), join(), zfill() 등을 종종 사용하는 편이네요. 



[ 파이썬 문자열 메소드 (String Methods in Python) ]



이번 포스팅은 https://www.tutorialspoint.com/python/python_strings.htm  사이트에 있는 영문 소개자료를 참고하여 작성하였습니다. 문자열 메소드의 기능 설명만 되어 있어서 좀더 이해하기 쉽도록 예제를 추가로 만들어보았습니다. 

expandtabs(), maketrans() 등 일부 메소드는 제가 써본적도 없고 앞으로 거의 쓸 일이 없을 것 같아서 주관적으로 판단해서 몇 개 빼고 소개하는 것도 있습니다. 


하나씩 예을 들어 살펴보겠습니다. 




1. 문자열 계산 관련 메소드 (String methods based on calculation)


len() : 문자열 길이



# len() : Returns the length of the string

>>> a = 'I Love Python'

>>> len(a)

13

 



 min(), max() : 문자열 내 문자, 혹은 숫자의 최소값, 최대값 (알파벳 순서, 숫자 순서 기반)



# max(str), min(str) : Returns the max, min alphabetical character from the string str

>>> d = 'abc'

>>> f = '123'

>>> 

>>> min(d)

'a'

>>> max(d)

'c'

>>> 

>>> min(f)

'1'

>>> max(f)

'3'

 



 count() :  문자열 안에서 매개변수로 입력한 문자열이 몇 개 들어있는지 개수를 셈 

                (begin, end 위치 설정 가능)



# count() : Counts how many times str occurs in string

>>> a = 'I Love Python'

>>> a.count('o')

2

>>> 

>>> a = 'I Love Python'

>>> a.count('o', 7, len(a)) # count(string, begin, end)

1

>>> 

>>> a.count('k') # there is no 'k' character in 'a' string

0

 





2. 문자열에 특정 문자 들어있는지 여부, 어디에 위치하고 있는지 찾아주는 메소드


  startswith() : 문자열이 매개변수로 입력한 문자열로 시작하면 True, 그렇지 않으면 False 반환



# startswith(): Determines if string or a substring of string

>>> a = 'I Love Python'

>>> a.startswith('I')

True

>>> a.startswith('I Lo')

True

>>> a.startswith('U')

False

 



  endswith() : 문자열이 매개변수로 입력한 문자열로 끝나면 True, 그렇지 않으면 False 반환



# endswith(): Determines if string or a substring of string

>>> a = 'I Love Python'

>>> a.endswith('Python')

True

>>> a.endswith('Pycham')

False

 



 find() : 문자열에 매개변수로 입력한 문자열이 있는지를 앞에서 부터 찾아 index 반환, 없으면 '-1' 반환



# find() : Search forwards, Determine if str occurs in string and return the index

>>> a = 'I Love Python'

>>> a.find('o')

3

>>> a.find('k') # if there is no string, then '-1'

-1

 



  rfind() : 문자열에 매개변수로 입력한 문자열이 있는지를 뒤에서 부터 찾아 index 반환, 없으면 '-1' 반환



# rfind() : Same as find(), but search backwards in string

>>> a = 'I Love Python'

>>> a.rfind('o')

11

 



 index() :  find()와 기능 동일하나, 매개변수로 입력한 문자열이 없으면 ValueError 발생



# index(): Same as find(), but raises an exception if str not found

>>> a = 'I Love Python'

>>> a.index('o')

3

>>> a.index('k') # ValueError: substring not found

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: substring not found

 



 rindex() : index()와 기능 동일하나, 뒤에서 부터 매개변수의 문자열이 있는지를 찾음



# rindex(): Same as index(), but search backwards in string

>>> a = 'I Love Python'

>>> a.rindex('o')

11

>>> a.rindex('k') # ValueError: substring not found

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: substring not found

 





3. 숫자, 문자 포함 여부 확인하는 메소드


  isalnum() : 문자열이 알파벳과 숫자로만 이루어졌으면 True, 그렇지 않으면 False



>>> a = 'I Love Python'

>>> d = 'abc'

>>> e = '123abc'

>>> f = '123'

>>> 

# isalnum() : Returns true if string has at least 1 character and 

#                  all characters are alphanumeric and false otherwise

>>> a.isalnum() # False

False

>>> d.isalnum() # True

True

>>> e.isalnum() # True

True

>>> f.isalnum() # True

True




  isalpha() : 문자열이 알파벳(영어, 한글 등)으로만 이루어졌으면 True, 그렇지 않으면 False



>>> a = 'I Love Python'

>>> d = 'abc'

>>> e = '123abc'

>>> f = '123'

>>> 

# isalpha() : Returns true if string has at least 1 character 

#                 and all characters are alphabetic and false otherwise

>>> a.isalpha() # False (there is space between characters)

False

>>> d.isalpha() # True

True

>>> e.isalpha() # False

False

>>> f.isalpha() # False

False




  isdigit() : 문자열이 숫자만 포함하고 있으면 True, 그렇지 않으면 False, isnumeric()과 동일



>>> a = 'I Love Python'

>>> d = 'abc'

>>> e = '123abc'

>>> f = '123'

>>> 

# isdigit() : Returns true if string contains only digits and false otherwise

>>> a.isdigit() # False 

False

>>> d.isdigit() # False

False

>>> e.isdigit() # False

False

>>> f.isdigit() # True

True




  isnumeric() : 문자열이 숫자로만 이루어져 있으면 True, 그렇지 않으면 False, isdigit()과 동일



>>> a = 'I Love Python'

>>> d = 'abc'

>>> e = '123abc'

>>> f = '123'

>>> 

# isnumeric(): Returns true if a unicode string contains only numeric characters

>>> a.isnumeric() # False

False

>>> d.isnumeric() # False

False

>>> e.isnumeric() # False

False

>>> f.isnumeric() # True

True

 



  isdecimal() : 문자열이 10진수 문자이면 True, 그렇지 않으면 False



>> a = 'I Love Python'

>>> d = 'abc'

>>> e = '123abc'

>>> f = '123'

>>> 

# isdecimal(): Returns true if a unicode string contains only decimal characters

>>> a.isdecimal() # False

False

>>> d.isdecimal() # False

False

>>> e.isdecimal() # False

False

>>> f.isdecimal() # True 

True

 





4. 대문자, 소문자 여부 확인하고 변환해주는 문자열 메소드


  islower() : 문자열이 모두 소문자로만 되어있으면 True, 그렇지 않으면 False



>>> a = 'I Love Python'

>>> g = 'i love python'

>>> h = 'I LOVE PYTHON'

>>> 

# islower(): Returns true if string has at least 1 cased character 

#            and all cased characters are in lowercase and false otherwise

>>> a.islower() # False

False

>>> g.islower() # True

True

>>> h.islower() # False

False

 



  isupper() : 문자열이 모두 대문자로만 되어있으면 True, 그렇지 않으면 False



>>> a = 'I Love Python'

>>> g = 'i love python'

>>> h = 'I LOVE PYTHON'

>>> 

# isupper(): Returns true if string has at least one cased character 

#           and all cased characters are in uppercase and false otherwise

>>> a.isupper() # False

False

>>> g.isupper() # False

False

>>> h.isupper() # True

True

 



  lower() : 문자열 내 모든 대문자를 모두 소문자(a lowercase letter)로 변환



>>> a = 'I Love Python'

>>> 

# lower(): Converts all uppercase letters in string to lowercase

>>> a.lower()

'i love python'




 upper() :  문자열 내 모든 소문자를 모두 대문자(a uppercase letter)로 변환



>>> a = 'I Love Python'

>>> 

# upper(): Converts lowercase letters in string to uppercase

>>> a.upper()

'I LOVE PYTHON'

 



 swapcase() : 문자열 내 소문자는 대문자로 변환, 대문자는 소문자로 변환



# swapcase(): Inverts case for all letters in string

>>> a = 'I Love Python'

>>> a.swapcase() # 'i lOVE pYTHON'

'i lOVE pYTHON'

>>> 

>>> g = 'i love python'

>>> g.swapcase() # 'I LOVE PYTHON' (same as upper())

'I LOVE PYTHON'

>>> 

>>> h = 'I LOVE PYTHON'

>>> h.swapcase() # 'i love python' (same as lower())

'i love python'

 



  istitle() : 문자열이 제목 형식에 맞게 대문자로 시작하고 이후는 소문자이면 True, 그렇지 않으면 False



>>> a = 'I Love Python'

>>> g = 'i love python'

>>> h = 'I LOVE PYTHON'

>>> 

# istitle(): Returns true if string is properly "titlecased" and false otherwise

>>> a.istitle() # True

True

>>> g.istitle() # False

False

>>> h.istitle() # False

False

 



 title() : 문자열을 제목 형식(titlecased)에 맞게 시작은 대문자로, 나머지는 소문자로 변환 



>>> g = 'i love python'

>>> h = 'I LOVE PYTHON'

>>> 

# title(): Returns "titlecased" version of string, that is, 

#          all words begin with uppercase and the rest are lowercase

>>> g.title() # 'I Love Python'

'I Love Python'

>>> h.title() # 'I Love Python'

'I Love Python'

 



  capitalize)=() : 문자열 내 첫번째 문자를 대문자로 변환하고, 나머지는 모두 소문자로 변환



>>> a = 'I Love Python'

>>> g = 'i love python'

>>> h = 'I LOVE PYTHON'

>>> 

# capitalize(): Capitalizes first letter of string

>>> a.capitalize() # 'I love python'

'I love python'

>>> g.capitalize() # 'I love python'

'I love python'

>>> h.capitalize() # 'I love python'

'I love python'

 





5. 공백 존재 여부 확인 및 처리하기 문자열 메소드 


 lstrip() : 문자열의 왼쪽에 있는 공백을 제거



# lstrip() : Removes all leading whitespace in string

>>> b = '      I Love Python'

>>> b.lstrip()

'I Love Python'




  rstrip() : 문자열의 오른쪽에 있는 공백을 제거



# rstrip() : Removes all trailing whitespace of string

>>> c = 'I Love Python      '

>>> c.rstrip()

'I Love Python'

 



  strip() : 문자열의 양쪽에 있는 공백을 제거



# strip() : Performs both lstrip() and rstrip() on string

>>> '     I Love Python     '.strip()

'I Love Python'

 



  isspace() : 문자열이 단지 공백(whitespace)으로만 되어있을 경우 True, 그렇지 않으면 False



# isspace(): Returns true if string contains only whitespace characters and false otherwise

>>> i = '     '

>>> j = '      I Love Python'

>>> 

>>> i.isspace() # True

True

>>> j.isspace() # False

False

 



  center(width) : 총 길이가 매개변수로 받는 문자열폭(width)만큼 되도록 공백을 추가하여 중앙 정렬



# center(): Returns a space-padded string with the original string 

#                centered to a total of width columns

>>> a = 'I Love Python'

>>> a.center(21)

'    I Love Python    '

 





6. 문자열을 나누고, 붙이고, 교체하고, 채우는 문자열 메소드 (split, join, replace, fill)


  split() : 문자열을 구분자(delimiter, separator) 기준에 따라 나누기


split()은 상당히 자주 사용하는 문자열 메소드 입니다. 



# split(): Splits string according to delimiter str (space if not provided) 

#    and returns list of substrings; split into at most num substrings if given

>>> x = 'haha, hoho, hihi'

>>> x.split(sep=',') # as a list ['haha', ' hoho', ' hihi']

['haha', ' hoho', ' hihi']




>>> ha, ho, hi = x.split(sep=',')

>>> ha

'haha'

>>> ho

' hoho'

>>> hi

' hihi'

 



>>> a = 'I Love Python'

>>> a.split(' ') # without arg 'sep='

['I', 'Love', 'Python']

>>> a.split() # default delimiter is space if not provided

['I', 'Love', 'Python'] 

 



  splitlines() : 여러개의 줄로 이루어진 문자열을 줄 별로 구분하여 리스트 생성



# splitlines(): returns a list with all the lines in string, 

#     optionally including the line breaks (if num is supplied and is true)

>>> y = 'haha, \nhoho, \nhihi'

>>> y

'haha, \nhoho, \nhihi'

>>> y.splitlines() # ['haha, ', 'hoho, ', 'hihi']

['haha, ', 'hoho, ', 'hihi']

 



 replace(old, new, max) : old 문자열을 new 문자열로 교체.  단, max 매개변수 있으면, max 개수 만큼만 교체하고 이후는 무시



# replace(old, new): Replaces all occurrences of old in string with new 

#        or at most max occurrences if max given

>>> a = 'I Love Python'

>>> a.replace('Python', 'R')

'I Love R'

>>> 

>>> 

>>> a_2 = 'I Love Python, Python, Python, Python, Python~!!!'

>>> a_2.replace('Python', 'R', 3) # str.replace(old, new, max)

'I Love R, R, R, Python, Python~!!!'




 join() :  여러개의 문자열을 구분자(separator) 문자열을 사이에 추가하여 붙이기


join()은 꽤 자주 쓰는 문자열 메소드 중의 하나입니다. 



# join(): Merges (concatenates) the string representations of elements 

#         in sequence seq into a string, with separator string

>>> mylist = ['I', 'Love', 'Python']

>>> print(mylist)

['I', 'Love', 'Python']

>>> 

>>> mystring = '_'.join(mylist)

>>> print(mystring) # 'I_Love_Python'

I_Love_Python

 



# To concatenate item in list to strings with join() method

>>> mylist_num = [1, 2, 3, 4, 5]

>>> print(mylist_num) # [1, 2, 3, 4, 5]

[1, 2, 3, 4, 5]

>>> 

>>> mylist_str = ''.join(map(str, mylist_num))

>>> print(mylist_str) # 12345

12345

>>> 

>>> '_'.join(map(str, mylist_num)) # '1_2_3_4_5'

'1_2_3_4_5'

 



 zfill(width) : 문자열을 매개변수 width만큼 길이로 만들되, 추가로 필요한 자리수만큼 '0'을 채움



# zfill(width): Returns original string leftpadded with zeros to a total of width characters; 

#      intended for numbers, zfill() retains any sign given (less one zero)

>>> f = '123'

>>> f.zfill(10)

'0000000123' 




 ljust(width[, fillchar]) : 문자열을 매개변수 width만큼 길이로 만들되, 왼쪽은 원본 문자열로 채우고, 

오른쪽에 추가로 필요한 자리수만큼 매개변수 fillchar 문자열로 채움



# ljust(): Returns a space-padded string with the original string left-justified 

#          to a total of width columns

# str.ljust(width[, fillchar])

>>> a = 'I Love Python'

>>> a.ljust(20, 'R')

'I Love PythonRRRRRRR'

 



 rjust(width[, fillchar]) : 문자열을 매개변수 width만큼 길이로 만들되, 오른쪽은 원본 문자열로 채우고, 

 왼쪽에 추가로 필요한 자리수만큼 매개변수 fillchar 문자열로 채움



# rjust(): Returns a space-padded string with the original string right-justified 

#          to a total of width columns

>>> a.rjust(20, 'R')

'RRRRRRRI Love Python'

>>> a.rjust(20, ' ')

'       I Love Python'

 



다음번 포스팅에서는 문자열의 포맷 메소드(string formatting opertor)에 대해서 알아보겠습니다. 


많은 도움 되었기를 바랍니다. 

이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. ^^



728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서는 R Base Graphics plotting system의


(1) 높은 수준의 그래프 함수 (high level graphic functions)

(2) 그래프 모수를 설정하는 2가지 방법 (2 methods of setting graphic parameters)

(3) 그래프 모수 : 기호(symbol), 선(line) 모양 및 크기

(4) 그래프 모수 : 색깔(color)

(5) 그래프 모수 : 그래프 영역 (plot area, inner margin area, outer margin area, multiple plot layout) 에 대해서 소개하였습니다.


높은 수준의 그래프 함수로 그래프의 골격을 만들수 있고, 그래픽 모수로 기호 모양이나 색, 크기 등을 설정할 수 있는데요, 이것 만으로는 원하는 그래프를 만드는데 부족함이 있습니다.  가령 그래프 제목을 추가하고 싶거나, 선이나 점을 추가하고 싶거나, 문자나 범례를 추가하고 싶다거나, XY축을 변경하고 싶을 때가 있는데요, 이때 추가적인 정보를 입력하기 위해 사용하는 것이 '낮은 수준의 그래프 함수 (Low level graphic functions)'가 되겠습니다.


높은 수준의 그래프 함수로 만약 plot(x, y, type = "n") 으로 하면 그래프 창만 열리고 plot area 안에는 빈 공간만 있게 되는데요, 여기에 낮은 수준의 그래프 함수로 그래프 기호, 선, 점, 범례 등을 추가해나갈 수도 있습니다.




이번 포스팅부터 수차례로 나누어서 낮은 수준의 그래프 함수(Low level graphic functions)에 대해서 차례대로 알아보도록 하겠습니다.


[ 낮은 수준의 그래프 함수 (Low level graphic functions) ]





먼저 (1) 그래프 제목(main/sub title) 및 XY축 라벨(XY axis label) 추가하는 방법으로 title() 함수에 대해서 소개해보겠습니다.  title() 함수에 사용하는 옵션으로는 주 제목 main, 부 제목 sub, X축 라벨 xlab, Y축 라벨 ylab 등이 있습니다.


 title(main = "main title to the top of plot in a large font",

      sub = "sub-title sub at the bottom in a smaller font",

      xlab = "x axis label",

      ylab = "y axis label")



이전 포스팅에서 소개했던 높은 수준의 그래프 함수, 즉 hist(), boxplot(), barplot(), plot() 등의 함수 안에서도 주 제목, 부 제목, X축 라벨, Y축 라벨을 직접 지정할 수 있는데요, 아래 예가 높은 수준읙 그래프 함수로 그린 그래프입니다.  


> ##----------------------------------------------
> ## adding main/sub title, XY axis label
> ##----------------------------------------------
> 
> library(MASS) # to use Cars93 dataframe
> 
> # method (1) high level graphic functions : plot()
> plot(MPG.highway ~ Weight, Cars93, 
+      main = "main title : scatter plot of Weight, MPG.highway", 
+      sub = "sub title : plotting with high level graphic functions", 
+      xlab = "x label : Weight", 
+      ylab = "y label : MPG.highway")



 




위의 그래프와 똑같은 그래프를 낮은 수준의 그래프 함수를 사용해서 그려보겠습니다.  먼저 높은 수준의 그래프 함수로는 "ann = FALSE" 옵션을 추가해서 기본 뼈대만 그려보겠습니다.  아래 그래프를 보시면 주 제목, 부 제목, X축 라벨, Y축 라벨이 하나도 없음을 알 수 있습니다.


> # tmheod (2) low level graphic functions : title()
> # deleting X and Y labels : ann = FALSE
> plot(MPG.highway ~ Weight, Cars93, ann = FALSE)



 




위의 기본 뼈대만 있는 그래프에 낮은 수준의 그래프 함수(Low level graphic function)를 사용해서 부가정보를 더해보도록 하겠습니다.


> # adding main title, sub title, x label, y label
> title(main = "main title : scatter plot of Weight, MPG.highway", 
+       sub = "sub title : plotting with low level graphic functions", 
+       xlab = "x label : Weight", 
+       ylab = "y label : MPG.highway")



 



높은 수준의 그래프 함수에서도 주 제목, 부 제목, XY축 Label 등을 설정할 수 있는데 왜 굳이 낮은 수준의 그래프 함수 title() 을 가지고 추가 정보를 입력하는지 의아할 수도 있겠습니다.  높은 수준의 그래프 함수 중에 부가정보를 입력할 수 없는 그래프 함수도 있으며, R의 장점 중에 하나가 대화형으로 그래프의 부가 정보를 차곡 차곡 쌓아가면서, 눈으로 확인해가면서 그릴 수 있어서 굉장히 직관적으로 탐색적 데이터 분석을 할 수 있다는 점입니다. 



참고로, 지난번 포스팅에서 소개한 그래프 모수 (graphics parameters) 중에서 기호의 크기를 설정하는 "cex.main = ", "cex.sub = ", "cex.lab = " 옵션을 사용해서 주 제목, 부 제목, XY축 Label의 크기를 변경해보겠습니다.


 

> # modification of font size : cex.main, cex.sub, cex.lab 
> 
> # deleting X and Y labels : ann = FALSE
> plot(MPG.highway ~ Weight, Cars93, ann = FALSE) 
> 
> # adding main title, sub title, x label, y label
> title(main = "main title with cex 2.2", 
+       sub = "sub title with cex 1.5", 
+       xlab = "x label with cex 1", 
+       ylab = "y label with cex 1", 
+       cex.main = 2.2, # main title size
+       cex.sub = 1.5, # sub title size
+       cex.lab = 1) # x and y label size




다음 포스팅에서는 낮은 수준의 그래프 함수 - (2) XY축 형태 변환 : axis(side, ...) 에 대해서 알아보도록 하겠습니다.


많은 도움이 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^


728x90
반응형
Posted by Rfriend
,