Python : 문자열에서 단일 또는 여러 문자를 대체하는 방법?

이 기사에서는 Python에서 문자열의 단일 또는 다중 문자를 대체하는 방법에 대해 설명합니다.

Python은 str.replace () 함수를 제공합니다. 즉

str.replace(old, new , count)

이는 대체 된 기존 문자열의 복사 본인 새 문자열 객체를 반환합니다. 함유량. 또한

  • count가 제공되지 않으면 모든 ‘old’항목이있는 문자열을 반환하고 ‘new’문자열로 대체합니다.
  • count 매개 변수가 전달되면 ‘이전’문자열이 ‘새’문자열로 대체 된 첫 번째 ‘횟수’문자열을 반환합니다.

예제를 통해 이해하겠습니다.

주어진 문자의 모든 발생을 대체합니다. / string in a string

문자열이 있다고 가정합니다. ie

mainStr = "Hello, This is a sample string"

이제 ‘s ‘with’X ‘ie

"""Replace all occurrences of given character or string in main string"""otherStr = mainStr.replace("s" , "X") 

otherStr의 내용은 다음과 같습니다.

Hello, ThiX iX a Xample Xtring

문자열은 파이썬에서 불변이므로 내용을 변경할 수 없습니다. 따라서 replace ()와 같은 멤버 함수는 새 문자열을 반환합니다.
replace () 함수에 count 매개 변수를 제공하지 않았기 때문입니다. 따라서 모든‘s’항목을‘X’로 바꿉니다. 그러나 모두가 아니라 처음 몇 개만 바꾸려면 어떻게해야합니까? 이를 수행하는 방법을 살펴 보겠습니다.

문자열에서 주어진 문자 / 하위 문자열의 처음 n 개 항목을 교체

문자열이 있다고 가정합니다. 즉

mainStr = "Hello, This is a sample string"

이제 ‘s’의 처음 2 개 항목을 ‘XXXS’로 바꾸겠습니다. 즉

"""Replace First 2 occurrences of given character or string in main string"""otherStr = mainStr.replace("s" , "XXXS", 2) 

otherStr의 내용은 다음과 같습니다.

Hello, ThiXXXS iXXXS a sample string

count 매개 변수를 2로 전달 했으므로 반환 된 사본에서 ‘s’의 처음 2 개 항목 만 대체됩니다.

여러 문자 대체 / strings in a string

str.replace () 함수는 주어진 하위 문자열의 발생 만 바꿀 수 있습니다. 하지만 주어진 문자열에서 여러 개의 하위 문자열을 교체하려면 어떻게해야합니까?

예를 들어 문자열이 있다고 가정합니다.

mainStr = "Hello, This is a sample string"

이제이 세 문자 ‘s’, ‘l’, ‘a’를이 문자열 ‘AA’로 대체하는 방법은 무엇입니까?
replace ()를 통해 새 함수를 만들어이를 수행합니다. 즉

"""Replace a set of multiple sub strings with a new string in main string."""def replaceMultiple(mainString, toBeReplaces, newString): # Iterate over the strings to be replaced for elem in toBeReplaces : # Check if string is in the main string if elem in mainString : # Replace the string mainString = mainString.replace(elem, newString) return mainString

List toBeReplaces의 모든 문자열을 mainString 목록의 newString으로 대체합니다.
어커런스를 “AA”로 바꾸는 방법을 살펴 보겠습니다.
otherStr의 내용은 다음과 같습니다.

HeAAAAo, ThiAA iAA AA AAAAmpAAe AAtring

완전한 예는 다음과 같습니다.
출력 :

String with replaced Content : Hello, ThiX iX a Xample XtringHello, ThiXXXS iXXXS a sample stringHeAAAAo, ThiAA iAA AA AAAAmpAAe AAtring

Write a Comment

이메일 주소를 발행하지 않을 것입니다. 필수 항목은 *(으)로 표시합니다