본문 바로가기
개발 언어/파이썬

# 0-0-5 22개의 필수적인 다양한 파이썬 문자열 메소드. [2022-02-19] Updated

by 괴짜코더 2022. 2. 18.

22 ESSENTIAL Python String Methods.

"""

Tip 		: 22 ESSENTIAL Python String Methods
Author 		: Python Engineer(Youtuber)
Source Link 	: https://www.youtube.com/watch?v=HJpiAZDJrRY
Date 		: This Document is Updated [2022-02-18] 

"""

# python file name = string-methods.py

"""****************************************************************"""

"""
1. Slicing 문자열내 해당 공간만 출력.
"""

example_string = '    hello    '
example_string_result = example_string[3:8]
print(example_string_result)

hello

"""
2. Strip('') 문자열을 뺀 빈공간 제거.
"""

example_string = '    hello    '.strip()
print(example_string)

hello

"""
3. Strip(#) .strip() 내 문자를 제거하고 나머지 문자값들을 출력.
"""

example_string = '###hello###'.strip(#)
print(example_string)

hello

"""
4. Strip('\n') .strip() 문자열내 줄바꿈 명령인수를 제거하고 \t 즉 탭은 허용하여 출력.
"""

example_string = ' \n \t hello\n'.strip('\n')
print(example_string)

	hello

"""
5. Strip('cmow.') .strip() cmow. 를 입력하면 www와 .com 사이 도메인 문자열만 빼내서 출력.
"""

example_string = 'www.naver.com'.strip('cmow.')
print(example_string)

naver

"""
6. lstrip('') and rstrip('') 문자열내 왼쪽의 빈 해당 공간만 또는 오른쪽의 빈 해당 공간만 출력.
"""

example_lstrip = '    hello    '.lstrip()
example_rstrip = '    hello    '.rstrip()

print(example_lstrip)
print(example_rstrip)

hello # 왼쪽 빈공간만 삭제했으나 오른쪽 빈 공간은 남아있다.
	hello # 오른쪽 빈공간만 삭제했으나 왼쪽 빈 공간은 남아있다.

"""
7. removeprefix('') and removesuffix('') 문자열내 왼쪽의 또는 오른쪽부터 옵션을 주고 잘라서 출력.
"""

example_lstrip = 'Arthur: three!'.lstrip('Arthur: ')
example_removeprefix = 'Arthur: three!'.removeprefix('Arthur: ')
example_removesuffix = 'HellowPython!'.removesuffix('Python')

print(example_lstrip)
print(example_removeprefix)
print(example_removesuffix)

ee!    # 'Arthur:  ' 문자열 내 문자각위치와 빈공간을 포함한 공간을 삭제하고 남은 문자들이다.
three! # 'Arthur:  ' 문자열 내 적혀있는 첫문자부터 시작한 공간만을 포함하여 삭제하고 남은 문자들이다.
Hellow # HellowPython 문자열 내 적혀있는 뒷문자부터 시작한 공간만을 포함하여 삭제하고 남은 문자들이다.

"""
8. replace('') 문자열내 해당 문자를 다른 문자로 바꿀수 있다.
"""

example_replace = 'string methods in python'.replace(' ', '-')

print(example_replace)

string-methods-in-python # 문자열 사이의 여백공간을 하이픈으로 바꾸었다.

"""
9. re.sub('') 정규 표현식을 이용한 빈 여백 삭제 또는 해당 문자를 다른 문자로 replace 할수있다. 
"""

example_re_sub1 = 'string    methods in python'
example_re_sub2 = 'string----methods-in-python'

example_re_sub_result1 = re.sub('\s+', '', example_re_sub1)
example_re_sub_result2 = re.sub('\s+', '-', example_re_sub2)

print(example_re_sub_result1)
print(example_re_sub_result2)

stringmethodsinpython # 빈 여백 공간을 지우고 출력한다.
string-methods-in-python # 중복된 문자만 삭제하고 출력한다.

"""
10. split('') 문자열과 문자열 사이를 쪼갤수 있다.
"""

# maxsplit 은 오브젝트에 선언된 문자열을 최대 몇개까지 쪼갤지 설정하는 옵션이다.
# lsplit 은 왼쪽에서 문자열을 쪼개기 시작할 스타트 포지션을 뜻한다.
# rsplit 은 오른쪽쪽에서 문자열을 쪼개기 시작할 스타트 포지션을 뜻한다.

example_split1 = 'string methods in python'.split(' ', maxsplit=1)
example_split2 = 'string methods in python'.lsplit(' ', maxsplit=1)
example_split3 = 'string methods in python'.rsplit(' ', maxsplit=1)

print(example_split1)
print(example_split2)
print(example_split3)

['string', 'methods in python'] # .split 은 default 셋팅 옵션은 lsplit 과 동일하다.
['string', 'methods in python'] # .lsplit 은 왼쪽에서부터 쪼갠다.
['string methods in', 'python'] # .rsplit 은 오른쪽에서 부터 쪼갠다.

"""
11. join() 쪼개어진 문자들을 하나로 합친다.
"""

example_list_of_strings = ['string', 'methods', 'in', 'python']
example_list_of_strings_result = '-'.join(example_list_of_strings)

print(example_list_of_strings_result)

string-methods-in-python # 배열내 원소들을 하나의 문자열들로 합치는데 원소들 사이에 하이픈을 추가해서 합친다.

"""
12. upper(), lower(), capitalize() 문자열의 소문자화, 대문자화, 대문자로 시작화.
"""

example_upper = 'python is awesome !'.upper()
example_lower = 'PYTHON IS AWESOME!'.lower()
example_capitalize = 'python is awesome !'.capitalize()

print(example_upper)
print(example_lower)
print(example_capitalize)

PYTHON IS AWESOME! # 문자열을 전부 대문자화 시킨다.
python is awesome! # 문자열을 전부 소문자화 시킨다.
Python is awesome! # 문자열의 첫번째만 대문자화로 시작한다.

"""
13. islower(), isupper() 문자열의 참 거짓 판별한다.
"""

print('PYTHON IS AWESOME!'.isupper()) # True
print('python is awesome!'.islower()) # True

print('PYTHON IS AWESOME!'.islower()) # False
print('python is awesome!'.isupper()) # False

"""
14. isalpha(), isnumeric(), isalnum() 알파벳인지, 숫자인지, 알파벳 또는 숫자인지 판별한다.
"""

alphabet = 'hellow'.isalpha()
numeric  = '4885'.isnumeric()
alnum    = 'areyou4885'.isalnum()
combined_alnum = 'areyou4885?'.isalnum()

print(alphabet) # 알파벳들로만 구성되어있는 문자임으로 True.
print(numeric) # 숫자들로만 구성되어있는 문자임으로 True.
print(alnum) # 알파벳 또는 숫자가 다들어있음으로 True.
print(combined_alnum) # 알파벳 또는 숫자가 들어있지만 특수기호가 있음으로 False.

"""
15. count('') 문자열내 특정한 문자의 갯수를 카운트 한다.
"""

example_count = 'hellow world'.count('o')

print(example_count)

2 # 알파벳 o 가 두개 들어가있음으로 2개가 카운트되어 나온다.

"""
16. find(''), lfind(''), rfind('') 문자열내 해당 문자또는 태그를 찾는다.
"""

example_find = 'Machine Learning'
idx = example_find.find('a', 1) # 문자열 내 첫번째 a의 위치를 찾는다.
idx2 = example_find.find('a', 2) # 문자열 내 두번째 a의 위치를 찾는다.
idx3 = example_find.lfind('a') # 문자열 내 첫번째에서 시작해서 첫번째 a의 위치를 찾는다.
idx4 = example_find.rfind('a') # 문자열 내 마지막에서 시작해서 첫번째 a의 위치를 찾는다.

print(idx)
print(idx2)
print(example_find[idx:])
print(example_find[idx2:])

1 # 문자열내에 a 첫번쨰 문자의 위치를 뜻한다.
10 # 문자열내에 a 두번째 문자의 위치를 뜻한다.
achine Learning # 슬라이싱을 이용하여 문자열내에 1번위치에서 마지막까지 출력한다.
arning # 슬라이싱을 이용하여 문자열내에 2번위치에서 마지막까지 출력한다.

"""
17. startswitch('') and endswitch('') 문자열의 시작과 끝부분을 검사하여 참 거짓인지 판별한다.
"""

print('Patrick'.startswitch('P')) # 문자열의 시작 문자 값이 P 와 동일함으로 True.
print('Patrick'.startswitch('ck')) # 문자열의 끝 문자열의 값이 ck 와 동일함으로 True.

"""
18. partition('') 문자열의 해당 문자열을 또는 문자를 기준으로 쪼갠다. 
"""

example_partition = 'Python is awesome!'

example_partition_result1 = example_partition.partition('is')
example_partition_result2 = example_partition.partition('was')

print(example_partition_result1)
print(example_partition_result2)

('Python','is','awesome!') #  example_partition 의 is를 기준으로 쪼개었다. a 'b' c
('Python is awesome!', '', '') # was를 기준으로 쪼개었지만 was는 문자열내 없기 때문에 'a' b c로 그리어진다.

"""
19. center(''), ljust(''), rjust('') 문자열 정렬하기.
"""

example_string = 'Python is awesome!'

center = example_string.center(30, '-')
ljust  = example_string.ljust(30, '-')
rjust  = example_string.rjust(30, '-')

print(center)
print(ljust)
print(rjust)

------Python is awesome!------ # 문자열을 가운데로 정렬하는데 얼만큼의 포인트와 어떤 문자로 묶어둘지 정한다.  
Python is awesome!------------ # 문자열을 왼쪽로 정렬하는데 얼만큼의 포인트와 어떤 문자로 묶어둘지 정한다.
------------Python is awesome! # 문자열을 오른쪽로 정렬하는데 얼만큼의 포인트와 어떤 문자로 묶어둘지 정한다.

"""
20. f-Strings f'{}' 변수 사이에 브라켓을 넣어서 다른 변수 값을 참조하여 사용한다. 
"""

num = 1
language = 'Python'
example_fstring = f'{language} is the number {num} in programming!'
print(example_fstring)

Python is the number 1 in programming! # 변수를 가져와서 example string 브라켓안에 넣어 사용한다.

"""
21. swapcase('') 대문자 또는 소문자로 치환한다.
"""

example_swapcase = 'HELLO world'
example_swapcase_result = example_swapcase.swapcase()
print(example_swapcase_result)

hello WORLD # lowercase uppercase 앞뒤 문자열을 바꿔준다.

"""
22. zfill('') 선언된 변수에 .zfill(num) num 매개변수로 문자열 공간 갯수를 정의해주고 남은 빈 공간은 0으로 채운다.
"""

example_string = '42'.zfill(5)
example_string = '-42'.zfill(5)

print(00042) # 5개의 공간임으로 남은 3개의 공간엔 0으로 채웠다.
print(-0042) # 5개의 공간에 2개의 공간에 0으로 채운다.

"""****************************************************************"""

댓글