본문 바로가기

Programming/Python

[Python] 문자열에서 특정 문자 삭제하기 : strip(), replace()

문자열에서 문자를 삭제하는 방법에는 여러가지가 있다. 그 중에 strip() 함수와 replace() 함수로 삭제하는 방법을 알아보려 한다.

 

 


 

strip()

문자열 양 끝에서 공백을 제거하거나 원하는 문자를 제거한다.

str = "     strawberry     "
result = str.strip()			# 'strawberry'
result = str.lstrip()			# 'strawberry     '
result = str.rstrip()			# '     strawberry'
str = ",,rrttgg.....strawberry..rrr"
result = str.strip(",.grt")		# 'strawberry'

 

replace()

문자열 내에 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환한다.

str = "this is a banana!"
str.replace("banana", "strawberry")	# 'this is a strawberry!'
str.replace("!", "")			# 'this is a strawberry'

 

728x90
728x90