알고리즘 문자열 문제를 위한 파이썬 정리

mmmYoung·2023년 4월 30일
0

알고리즘

목록 보기
13/13

String 함수

split

string.split(separator, maxsplit)

특정 문자를 기준으로 나누는 것. separator의 기본 값은 공백이므로, 기본적으로 공백을 기준으로 나눠준다. maxsplit은 최대 몇번이나 나눌지에 대한 제한횟수.

text = 'Hello world, python,hi'
result1 = text.split()
result2 = text.split(',')
result3 = text.split(',',1)

result1 = ['Hello', 'world,', 'python,hi']
result2 = ['Hello world', 'python', 'hi']
result3 = ['Hello world', 'python,hi'] (한번만 split)

slice

string[start:end:step]

s = "abcdefgh" 일 때,
s[1:4]는 index=1 ~ index= 3까지의 문자열을 슬라이싱한다.
s[-4:-1]는 index= -4 ~ index = -2 까지의 문자열 슬라이싱.
s[-3:]은 마지막에서 3글자를 가져온다.
s[:5]은 처음부터 index=4까지.

s = "abcdefgh"
s[1:4] = "bcd"
s[-4:-1] = "efg"
s[-3:] = "fgh"
s[:5] = "abcde"

For문

for문은 반복 도중에 변수를 수정해도 기존의 동작에는 영향을 주지 않는다.
아래처럼 c++ for문 안에서 i값을 변경하는 코드는 안 먹혀서 while 루프를 이용해야 함!

for(int i=0; i<5; i++){
	i =index;
}

index가 필요한 반복문

1. 직접 i 변수를 생성

i = 0
examples = ["a", "b", "c"]

for example in examples:
    i = i + 1

2.range를 이용하여 접근

for i in range(len(examples)):

3. enumerate()를 이용하여 요소와 index를 접근

for i, element in enumerate(examples):
    print(f'Index: {i}, Element: {element}')

시작 인덱스 값을 바꾸고 싶다면?

for i, element in enumerate(examples,start=2):
    print(f'Index: {i}, Element: {element}')

튜플을 이용해서 인덱스,요소 값을 받아오는 법도 있다

for example in enumerate(examples):
    print(examples)
    print(f'Index: {examples[0]}, Element: {examples[1]}')
    

출력
(0,'a')
Index: 0, Element: a
(0,'b')
Index: 1, Element: b
(0,'c')
Index: 2, Element: c

profile
안냐세여

0개의 댓글