Python 문자열 처리 방법

count() 메서드

count() 메서드는 문자열에서 특정 문자가 등장하는 횟수를 반환합니다. 시작과 끝 위치를 지정할 수 있습니다.

  
name = 'xiaoming'
print(name.count('i')) # 0부터 끝까지
print(name.count('i', 2, 4)) # 2부터 4까지
print(name.count('i', 2, 6)) # 2부터 6까지
  
  

결과:

  
2
0
1
  
  

index() 메서드

index() 메서드는 문자열에서 특정 서브스트링이 포함되어 있는지 확인하고, 포함되어 있다면 그 위치를 반환합니다. 만약 지정된 범위 내에 서브스트링이 없다면 예외를 발생시킵니다.

  
str1 = "this is string example....wow!!!"
str2 = "exam"

print(str1.index(str2))
print(str1.index(str2, 10))
print(str1.index(str2, 40))
  
  

결과:

  
15
15
Traceback (most recent call last):
  File "test.py", line 8, in 
  print str1.index(str2, 40);
ValueError: substring not found
  
  

split() 메서드

split() 메서드는 지정된 구분자를 사용하여 문자열을 분할합니다. num 매개변수가 지정되면 num+1 개의 서브스트링으로 분할됩니다.

  
tr = "Line1-abcdef \nLine2-abc \nLine4-abcd"
print(tr.split()) # 공백 및 \n을 기준으로 분할
print(tr.split(' ', 1)) # 첫 번째 공백까지만 분할
  
  

결과:

  
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
  
  

strip() 메서드

strip() 메서드는 문자열의 앞뒤에서 지정된 문자를 제거합니다. 기본적으로 공백 또는 줄 바꿈 문자를 제거합니다.

  
str1 = "00003210Runoob012300000"
print(str1.strip('0')) # 0 제거

str2 = " Runoob "
print(str2.strip()) # 공백 제거
  
  

결과:

  
3210Runoob0123
Runoob
  
  

join() 메서드

join() 메서드는 시퀀스의 요소를 지정된 문자로 연결하여 새로운 문자열을 생성합니다.

  
names = ['1','2','3','4','5']
result = '@'.join(names)
print(result)
print(type(result))

seq = ("a", "b", "c")
print('-'.join(seq))

str = 'abcd'
print(','.join(str))
  
  

결과:

  
1@2@3@4@5
<class 'str'>
a-b-c
a,b,c,d
  
  

startswith() 메서드

startswith() 메서드는 문자열이 특정 서브스트링으로 시작하는지 확인합니다.

  
tr = "this is string example....wow!!!"
print(tr.startswith('this'))
print(tr.startswith('is', 2, 4))
print(tr.startswith('this', 2, 4))
  
  

결과:

  
True
True
False
  
  

endswith() 메서드

endswith() 메서드는 문자열이 특정 서브스트링으로 끝나는지 확인합니다.

  
str = "this is string example....wow!!!"
suffix = "wow!!!"
print(str.endswith(suffix))
print(str.endswith(suffix, 20))

suffix = "is"
print(str.endswith(suffix, 2, 4))
print(str.endswith(suffix, 2, 6))
  
  

결과:

  
True
True
True
False
  
  

upper() 메서드

upper() 메서드는 문자열의 모든 소문자를 대문자로 변환합니다.

  
str = "this is string example....wow!!!"
print(str.upper())
  
  

결과:

  
THIS IS STRING EXAMPLE....WOW!!!
  
  

lower() 메서드

lower() 메서드는 문자열의 모든 대문자를 소문자로 변환합니다.

  
str = "THIS IS STRING EXAMPLE....WOW!!!"
print(str.lower())
  
  

결과:

  
this is string example....wow!!!
  
  

zfill() 메서드

zfill() 메서드는 문자열의 길이를 지정된 길이로 맞추고, 부족한 부분은 0으로 채웁니다.

  
str = "this is string example....wow!!!"
print(str.zfill(40))
print(str.zfill(50))
  
  

결과:

  
00000000this is string example....wow!!!
000000000000000000this is string example....wow!!!
  
  

enumerate() 함수

enumerate() 함수는 반복 가능한 객체를 인덱스와 함께 열거합니다.

  
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
for s in enumerate(seasons):
    print(s)

for s in enumerate(seasons, 3):
    print(s)
  
  

결과:

  
(0, 'Spring')
(1, 'Summer')
(2, 'Fall')
(3, 'Winter')

(3, 'Spring')
(4, 'Summer')
(5, 'Fall')
(6, 'Winter')
  
  

ljust() 메서드

ljust() 메서드는 문자열을 왼쪽 정렬하고, 지정된 길이만큼 오른쪽을 공백으로 채웁니다.

  
while True:
    try:
        s = input("문자열 입력: ")
        while len(s) > 8:
            print("s[:8]", s[:8])
            s = s[8:]
        print("s.ljust", s.ljust(8, "0"))
    except:
        break
  
  

결과:

  
문자열 입력: 1234567890987654321
s[:8] 12345678
s[:8] 90987654
s.ljust 32100000
  
  

find() 메서드

find() 메서드는 문자열에서 특정 서브스트링이 처음 등장하는 위치를 반환합니다. 서브스트링이 없으면 -1을 반환합니다.

  
info = 'abca'
print(info.find('a'))      # 0부터 시작
print(info.find('a', 1))   # 1부터 시작
print(info.find('3'))      # 찾을 수 없는 경우
  
  

결과:

  
0
3
-1
  
  

round() 함수

round() 함수는 주어진 숫자를 반올림합니다.

  
print(round(80.23456, 2))
print(round(100.000056, 3))
print(round(-100.000056, 3))
  
  

결과:

  
80.23
100.0
-100.0
  
  

replace() 메서드

replace() 메서드는 문자열에서 특정 서브스트링을 다른 문자열로 대체합니다. max 매개변수가 지정되면 최대 대체 횟수를 제한합니다.

  
str = "this is string example....wow!!! this is really string"
print(str.replace("is", "was"))
print(str.replace("is", "was", 3))
  
  

결과:

  
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
  
  

태그: python 문자열 메서드 count Index

8월 13일 08:54에 게시됨