Programming/Python

[PY4E/AI] 파이썬 문자열; index slicing find startswith endswith upper() lower() capitalize() titile() relpace strip() center

aram 2022. 7. 10. 14:47

1. index

- 문자열의 각 문제는 개별 주소(offset)를 가짐

- 이 주소(각 번호)를 사용해 할당된 값을 가져오는 것 = 인덱싱indexing

- List와 같은 형태로 데이터 처리

- input : 문자열로 입력값을 불러움

- 각 문자의 오프셋 시작 = fur[0] : 왼쪽) 0부터 시작 함 / 오른쪽) -1부터 시작

- 문자열 크기를 넘어서면 error → len(furit) : 문자열 길이 반환 → 그 길이만큼 활용

fruit = 'banana'
index = 0

# while 불확정 루프
while index < len(fruit) :
    letter = fruit[index]
    print(index, letter)
    index = index + 1

# for 유한 루프
for letter in fruit :
    print(letter)
    
## 결과값 ##
# 0 b
# 1 a
# 2 n
# 3 a
# 4 n
# 5 a

☞ for 루프가 훨씬 간단함 = 실수할 가능성이 적음 

 

2. in

- 반복 변수(letter)는 시퀀스(fruit)를 통해 반복

- print는 시퀀스 안에 있는 값 하나에 한 번씩 '실행 반복'

for letter in 'banana': print(letter)

 

3. Slicing Strings

- ' '(콜론 연산자)를 사용 → 문자열의 연속적인 구간 가져옴

 

'Monty Python'

M o n t y   P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11

- [2 : 7] 두번째 숫자는 마지막 index 포함X

s = 'Monty Python'
print(s[2:7]) #nty P

- [6 : 20] 문자열 너머를 가리키는 경우, 마지막에서 STOP

- [-50 : 50] 범위를 넘어갈 경우 자동으로 최대 범위 지정

print(s[6:20]) #Python 11번째 주소에서 자동 정지
print(s[-50:50]) #Monty Python 최대범위

- [2 : 8 : 2] 앞의 두개는 범위, 세 번째는 건너뛰어서 실행

print(s[2:8:2]) #nyP

- [::2] or [::-2] 2칸 단위로, 역으로 슬라이싱

print(s[::2]) #MnyPto
print(s[::-2]) #nhy to

- [ : 2] or [2 : ] 각각 문자의 시작과 마지막 가리킨다고 가정

- [ : ] 전체 실행

print(s[:2]) #Mo   
print(s[2:]) #nty Python
print(s[:]) #Monty Python

 

4. 문자열 병합  : '+' 연산자 사용

>>> a = 'Monty'
>>> b = 'Python'
>>> c = a + 'Python'
>>> print(c)
MontyPython

>>> d = a + ' ' + b
>>> print(d)
Monty Python

 

5. in 논리연산자(True / False check)

- 어떤 문자열이 다른 문자열에 "포함" 여부를 확인

- if 구문에 사용될 수 있음

>>> fruit = 'banana'
>>> print('n' in fruit)
True
>>> print('m' in fruit)
False
>>> print('nan' in fruit)
True

>>> if 'a' in fruit :
...     print('Found it!')

Found it

 

6. 문자열 비교

- 일반적으로 대문자 > 소문자 but 설정에 따라 소문자가 먼저 오기도 함.

- 대소문자, 특수문자가 있으면 이상하게 정열될 수 있음 >> 이 경우가 아니면 제대로 작동

- lower()로 모두 소문자로 바꾼 뒤 탐색 >> 대소문자와 관계없이 find()로 문자열 탐색 가능

>>> a = 'Monty'
>>> b = 'Python'
>>> 
>>> if a < b : 
...     print("a < b", b)
>>> else :
...     print("a >= b", a)

a < b Python

 

7. 문자열 라이브러리(Library)

- 문자열 객체는 메소드 이미 내장

- 기존 문자열은 변화X  / 메소드 호출 시, 복사본을 실행

- 객체지향 함수 : X.someing()

>>> a = 'Monty'
>>> print(type(a))
<class 'str'>

>>> print(dir(a))
['__add__', 
'__class__', '__contains__', 
'__delattr__', '__dir__', '__doc__', 
'__eq__', 
'__format__', 
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', 
'__hash__', 
'__init__', '__init_subclass__', '__iter__', 
'__le__', '__len__', '__lt__', 
'__mod__', '__mul__', 
'__ne__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', 
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 

'capitalize', 'casefold', 'center', 'count', 
'encode', 'endswith', 'expandtabs', 
'find', 'format', 'format_map', 
'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 
'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 
'join', 
'ljust', 'lower', 'lstrip', 
'maketrans', 
'partition', 
'removeprefix', 'removesuffix', 'replace', 'rfind', 
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 
'title', 'translate', 
'upper', 
'zfill']

 

#문자열_찾기

str.find(sub[, start[, end]]) - sub이 왼쪽 끝부터 시작하여 몇 번째 있는지 반환

str.rfind(sub[, start[, end]]) - sub이 오른쪽 끝부터 시작하여 몇 번째에 있는 지 반환

: 하위 문자열을 다른 문자열에서 탐색 가능

: 첫 번째로 나타나는 위치(오프셋) 반환

: 찾지 못하면, -1 반환

# 문자열에서 숫자 추출하는 패턴 만들기
>>> str = 'X-DSPM-Confidence: 0.8475'
>>> ipos = str.find(':')
>>> print(ipos)
17
>>> piece = str[ipos+2:]
>>> print(piece)
0.8475
>>> value = float(piece)
>>> print(value)
0.8475

 

str.startswith(suffix[, start[, end]]) - 시작문자열 찾기
str.endswith(suffix[, start[, end]]) - 끝 문자열 찾기

>>> line = 'Please have a nice day' 
>>> a = line.startswith('Please') 
>>> print(a)
True
>>> b = line.startswith('p') 
>>> print(b)
False
>>> c = line.endswith('y') 
>>> print(c)
True

 

#문자열_숫자 

count(sub) - sub이 몇 개 있는지 개수 반환

with open("yesterday.txt", "r") as f:
    content = f.read().lower()
    print("Number of a Word 'Yesterday'", content.count("yesterday"))
#Number of a Word 'Yesterday' 9

 

#대소문자 

str.upper() - 모두 대문자
str.lower()  - 모두 소문자
str.capitalize() - 첫 번째 문자만 대문자
str.title() - 제목형태로 변환, 띄워쓰기 후 각 단어의 첫글자만 대문자

>>> str = 'X-DSPM-Confidence: 0.8475'
>>> nnn = str.upper() 
>>> print(nnn) 
X-DSPM-CONFIDENCE: 0.8475 

>>> www = str.lower() 
>>> print(www) 
x-dspm-confidence: 0.8475

>>> c = str.capitalize()
>>> print(c)
X-dspm-confidence: 0.8475

>>> d = str.title()
>>> print(d)
X-Dspm-Confidence: 0.8475

 

#찾아서_바꾸기 str.replace(old, new[, count]) 

            문자열.replace(치환하고 싶은 문자열, 새로운 문자, 치환 횟수)

: 나타나는 모든 탐색 문자열을 대체 문자열로 치환

# str_data에서 '{', '}' 제거

>>> str_data = '{Hey} {Jude} {don"t be {{afraid'
>>> print('str_data', str_data)
str_data {Hey} {Jude} {don"t be {{afraid

>>> pre_str_data1 = str_data.replace('{', '')
>>> print(pre_str_data1)
Hey} Jude} don"t be afraid

>>> pre_str_data2 = pre_str_data1.replace('}', '')
>>> print(pre_str_data2)
Hey Jude don"t be afraid

 

#공백제거
str.lstrip([chars]) - 문자열의 왼쪽 공백 제거
str.rstrip([chars]) - 문자열의 오른쪽 공백 제거
str.strip([chars]) - 문자열의 시작과 끝에 있는 모든 공백 제거
공백 : 단순히 띄어쓰기가 아니라 보이진 않지만 출력되지 않는 다른 문자 역시 포함
          Tab(탭문자), Newlim(새줄문자) 등, 출력이 일어나지 않도록 하는 모든 종류의 문자

>>> greet = ' Hello Bob ' 
>>> greet.lstrip() 
'Hello Bob ' 
>>> greet.rstrip() 
' Hello Bob' 
>>> greet.strip() 
'Hello Bob'

 

#문자열 정렬
str.center(width[, fillchar]) 

: 길이만큼 문자열을 중앙 정렬 → 나머지는 채움문자로 채워서 반환
: 채움문자가 없으면 공백으로 반환
str.ljust(width[, fillchar]) : 길이만큼 문자열 왼쪽 정렬
str.rjust(width[, fillchar]) : 길이만큼 문자열 오른쪽 정렬

greet = 'Hello Bob' 
new_greet = greet.center(24, "*")
print(len(new_greet)) # 24
print(new_greet) #*******Hello Bob********
print('***', greet.ljust(24), '***') # *** Hello Bob                ***
print('***', greet.rjust(24), '***') # ***                Hello Bob ***

 

#리스트_반환
str.split() - 공백을 기준으로 나눠 리스트로 반환
str.split('abc') - abc를 기준으로 나눠 리스트로 반환

>>> title = "TEAMLAB X Upstage"
>>> title.split(" ") 
['TEAMLAB', 'X', 'Upstage']

 

#문자열_판단
str.isdigit() - 문자열이 숫자인지 여부 반환
str.islower() - 문자열이 소문자인지 여부 반환
str.isupper() - 문자열이 대문자인지 여부 반환

>>> title = "TEAMLAB X Upstage"
>>> title.isdigit() 
False
>>> "12345".isdigit() 
True

 

#문자열_자르고_합치기
str.split([기준값]) - 문자열을 단어 단위로 기준값(생략 시 공백)으로 나눠서 리스트list로 반환
str.splitlines([기준값]) - 문자열을 한 줄 단위로 기준값(생략 시 공백)으로 나눠서 리스트list로  반환
str.join() - 문자열의 각 문자 사이에 다른 문자열 끼워넣음

예시 >> https://dailystudy.tistory.com/50 

 

8. 문자열 표현

  • It’s의 ' 표현
    • a = ‘It\’ ok.’ : [ \ ]는 문자열 구분자가 아닌 출력 문자로 처리
    • a = “It’s ok.” : 큰따옴표("")로 문자열 선언작은 따옴표(')는 출력 문자로 사용
  • 두줄 이상은 어떻게 저장할까?
    • \n : 줄바꿈을 의미하는 특수 문자
    • 큰따옴표 또는 작은 따옴표 세 번 연속 사용
>>> a = '''It's ok
. . .  I'm happy
. . .  See you.'''
  • 백슬래시 “\”  사용 > 키보드로 표시하기 어려운 문자들을 표현함

<출처> 인공지능(AI) 기초 다지기 / 부스트코스

  • raw string : 특수문자 특수 기호인 \ 이스케이프escape 글자를 무시하고 그대로 출력함
>>> raw_string = "빨리 집에 가자. \n빨리!!"
>>> print(raw_string)
빨리 집에 가자.
빨리!!
>>> raw_string = r"빨리 집에 가자. \n빨리!!"
>>> print(raw_string)
빨리 집에 가자. \n빨리!!

 

* 내용참고&출처 : 태그의 수업을 복습 목적으로 정리한 내용입니다.

728x90