Image Source : Quick and Dirty Tips
이번 포스팅에서는 Python의 String Methods에 대하여 살펴보겠습니다. 포스트의 내용은 Jupyter notebooks에 작성해놓은 코드를 그대로 옮긴 것입니다. 그렇기에 단순히 '메서드가 어떤 방식으로 동작하는지에 관해 살펴보는 용도'로 읽어보시면 됩니다.
String
다른 무수한 프로그래밍 언어처럼 파이썬의 문자열도 배열입니다. 그렇기에 square brackets([ ])으로 문자열의 각각의 요소에 접근이 가능합니다. 또다른 특징으로는 Immutable, 즉 변경불가한 값입니다.
String Constants
# 주석으로 표현한 부분은 출력값 입니다. 우물정(#)자는 무시해주세요. # 다음부터가 실제 출력값입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import string print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.digits) # 0123456789 print(string.hexdigits) # 0123456789abcdefABCDEF print(string.octdigits) # 01234567 print(string.punctuation) #!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ print('hello'+string.whitespace+'This is Baby Tiger') #hello #This is Baby Tiger |
Multiline Strings
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | a = """Let's write down a multiline Here and There Hello I I I Miss You """ print(a) #Let's try write down multiline #Here #and #There #Hello #I #I #I #Miss #You |
Slicing
slicing과 연산의 조화
Strip
1 2 3 4 5 6 7 | a = " Plz KILL white spaces in front of string" print(a) # Plz KILL white spaces in front of string print(a.strip()) #Plz KILL white spaces in front of string |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #how many spaces that strip can hold? s5 = " 5 spaces" s10 = " 10 spaces" print(s5) # 5 spaces print(s5.strip()) #5 spaces print(s10) # 10 spaces print(s10.strip()) #10 spaces |
Lower & Upper
isupper() & islower()
1 2 3 4 5 6 7 8 9 10 11 12 | letter_case = "this is lower cases" print(letter_case.isupper()) #False print(letter_case.islower()) #True print((letter_case.upper()).isupper()) #True print(letter_case.upper().isupper()) #True |
swapcase()
1 2 3 4 5 6 7 8 | lower_only = "we won yes so dam happy!" upper_only = "WE WON YES SO DAM HAPPY!" print(lower_only.swapcase()) #WE WON YES SO DAM HAPPY! print(upper_only.swapcase()) #we won yes so dam happy! |
Replace
1 2 3 4 5 6 7 8 | phr = "You are stronger than you believe." print(phr.replace(" ", "!")) #You!are!stronger!than!you!believe. print(phr.replace("y", "***")) #You are stronger than *** believe. |
1 2 3 4 5 6 7 8 | numb = "0109994468" print(numb.replace("9", "*")) #010***4468 sfnumb = "4155313333" print(sfnumb.replace("415", "San Francisco Area Code ")) #San Francisco Area Code 5313333 |
1 2 3 4 5 6 7 | same = "333" print(sfnum) #4155313333 print(sfnum.replace(same,"+")) #415531+3 |
Replace와 다른 Method의 조합
1 2 3 4 5 6 7 | # Repalce + upper wonder = "If no one else will defend the world, then I must." find = "must" print(wonder.replace(find, find.upper())) #If no one else will defend the world, then I MUST. |
split()
comma = "Hello, world" print(comma.split(",")) #['Hello', ' world'] separated = comma.split(",") print(separated) #['Hello', ' world'] print(type(separated)) #<class 'list'> | cs |
1 2 3 4 | anno_num = "44400801133600334250353" print(anno_num.split("0")) #['444', '', '8', '11336', '', '33425', '353'] |
1 2 3 4 5 6 7 8 9 10 11 12 | truth = """ Integrity is telling myself the truth. And honesty is telling the truth to other people """ print(truth.split("i")) #['\nIntegr', 'ty ', 's tell', 'ng myself the truth. \nAnd honesty ', #'s tell', 'ng the truth to other people\n'] print(truth.split("telling")) #['\nIntegrity is ', ' myself the truth. #\nAnd honesty is ', ' the truth to other people\n'] |
Check string
1 2 3 4 5 6 7 8 9 10 | txt = "Sincerity, personal integrity, humility, courtesy, wisdom, charity." x = "humility" in txt print(x) #True y = "humility" not in txt print(y) #False |
numm = "009989038683830783868" two = "2" in numm print(two) #False two_not = "2" not in numm print(two_not) #True check = "3868" in numm print(check) #True |
Concatenation
a = "Ling" b = " Ling" c = a + b print(c) #Ling Ling |
a = "please" b = "take" c = "five" print(a + b + c) #pleasetakefive print(a + " " + b + " " + c) #please take five |
age = 28 txt = "My Name is Baby, I am " + age print(txt) |
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-140-23e7d3013a68> in <module> 1 age = 28 ----> 2 txt = "My Name is Baby, I am " + age 3 print(txt) TypeError: can only concatenate str (not "int") to str |
format()
age = 27 txt = "My name is Baby, and I am {}" print(txt.format(age)) #My name is Baby, and I am 27 |
age = 27 txt1 = "My name is Baby, and I am" + age print(txt.format(age)) |
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-226-0c8d41010a94> in <module> 3 print(txt.format(age)) 4 ----> 5 txt1 = "My name is Baby, and I am" + age 6 print(txt.format(age)) TypeError: can only concatenate str (not "int") to str |
txt2 = "{} 1 and two {}" print(txt2.format(age)) |
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-146-d972a2d08146> in <module> 1 txt2 = "{} 1 and two {}" ----> 2 print(txt2.format(age)) IndexError: tuple index out of range |
age = 27 txt2 = "{} 1 and two {}" print(txt2.format(age,age)) #27 1 and two 27 |
truth = "{} loves {}, but {} loves {}" person1 = "Tim" person2 = "Baby" person3 = "Brown" print(truth.format(person1, person2, person2, person3)) #Tim loves Baby, but Baby loves Brown |
여기서 주의해야 할 것은 person1, 2, 3 에 담긴것은 string 이기 때문에 "" 를 붙여주어야 한다. !! 잊지 말것 !!
quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price)) #I want to pay 49.95 dollars for 3 pieces of item 567. |
numbering 을 통해 들어오는 인자의 순서를 바꿀 수 있다. { } 사이에 들어온 인자의 순서대로 넣어준다. 주의 할 점은 0 부터 인자의 순서가 시작 된다는 것.
num1 = 1 num2 = 2 num3 = 3 discript = "I'm number {} and {} also {}" print(discript.format(num3, num1, num2)) #I'm number 3 and 1 also 2 by_order = "I'm number {1} and {2} also {0}" print(by_order.format(num3, num1, num2)) #I'm number 1 and 2 also 3 |
title()
book = "wit and wisdom" x = book.title() print(x) #Wit And Wisdom |
low = "every first letter is lower case" upper = low.title() print(upper) #Every First Letter Is Lower Case |
하지만 첫 글자에 숫자가 오게 되면 어떻게 될까? 오류가 날까?
mixture = "some first letter 1contains numbers" upp = mixture.title() print(upp) #Some First Letter 1Contains Numbers |
오호! 숫자는 건너 뛰고 무조건 string 타입의 첫 element 를 만났을때 변경해주는 군.
new_mixture = "what about 11123this" uppp = new_mixture.title() print(uppp) #What About 11123This |
istitle()
new_mixture = "what about 11123this" uppp = new_mixture.title() print(new_mixture.istitle()) #False print(uppp.istitle()) #True |
zfill()
fill_me = "50" x = fill_me.zfill(10) print(x) #0000000050 |
fill3 = abc.zfill(3) fill10 = abc.zfill(10) print(fill3) #abc print(fill10) #0000000abc |
tw = "twice" length = len(tw) fillout = tw.zfill(length*2) fillout3 = tw.zfill(length**2) print(fillout) #00000twice print(fillout3) #00000000000000000000twice print(type(fillout)) #<class 'str'> print(tw+fillout3) #twice00000000000000000000twice |
isspace()
txt = " " x = txt.isspace() print(x) #True only_one_space = "bunchofwordsandther's onlyonespace" y = only_one_space.isspace() print(y) #False |
isnumeric()
nume = "8375920" print(nume.isnumeric()) #True |
nume_with_char = "8678i'm0888here" print(nume_with_char.isnumeric()) #False |
보다시피 숫자로만 이루어져있는 string이어야 한다.
isalpha()
isthis = "spaceX" print(isthis.isalpha()) #True print(isthis.isnumeric()) #False |
alpha_w_numb = "spaceX 2019" alpha_w_symb = "space X ** 2019" print(alpha_w_numb.isalpha()) #False print(alpha_w_symb.isalpha()) #False |
정말 순수하게 알파벳으로만 이루어져 있어야 한다.