Python – 문자열에서 하위 문자열의 모든 항목 바꾸기

때로는 Python 문자열로 작업하는 동안 모든 하위 문자열을 다른 문자열로 바꿔야 하는 문제가 발생할 수 있습니다.

입력 : test_str = geeksforgeeks s1 = 괴짜 s2 = abcd
출력 : test_str = abcdforabcd 설명 : test_str에서 s1의 모든 항목을 s2로 바꿉니다.

입력 : test_str = geeksforgeeks s1 = for s2 = abcd
출력 : test_str = geeksabcdgeeks

접근법 1

python3에 있는 내장 함수 바꾸기를 사용하여 모든 하위 문자열을 바꿀 수 있습니다.

내장 기능을 사용한 구현:-

파이썬3




#Python has inbuilt function replace to replace all occurrences of substring.> input_string> => 'geeksforgeeks'> s1> => 'geeks'> s2> => 'abcd'> input_string> => input_string.replace(s1, s2)> print> (input_string)>

산출

abcdforabcd 

시간 복잡도: 에)
보조 공간: 에)

접근법 2:

문자열을 하위 문자열로 분할한 다음 새 string.split() 함수로 바꾸는 것이 사용됩니다.

파이썬3




#code for replacing all occurrences of substring s1 with new string s2> test_str> => 'geeksforgeeks'> s1> => 'geeks'> s2> => 'abcd'> #string split by substring> s> => test_str.split(s1)> new_str> => ''> for> i> in> s:> > if> (i> => => ''):> > new_str> +> => s2> > else> :> > new_str> +> => i> #printing the replaced string> print> (new_str)> #contributed by Bhavya Koganti>

산출

abcdforabcd 

모든 방법의 시간 및 공간 복잡도는 동일합니다.

시간 복잡도: 에)

보조 공간: 에)

방법 3: 문자열에서 부분 문자열을 모두 바꾸는 또 다른 방법은 다음을 사용하는 것입니다. re.sub() Python의 re 모듈에 있는 함수입니다.

파이썬3




import> re> def> replace_substring(test_str, s1, s2):> > # Replacing all occurrences of substring s1 with s2> > test_str> => re.sub(s1, s2, test_str)> > return> test_str> # test> test_str> => 'geeksforgeeks'> s1> => 'geeks'> s2> => 'abcd'> print> (replace_substring(test_str, s1, s2))>

산출

abcdforabcd 

시간 복잡도: O(n), 여기서 n은 입력 문자열의 길이입니다. 이는 re.sub() 함수가 전체 입력 문자열을 반복하고 각 문자에 대해 정규식 일치를 수행하여 하위 문자열의 모든 항목을 찾기 때문입니다. 반복 횟수는 입력 문자열의 길이에 정비례합니다.
보조공간:신규

방법 4: 단순 반복 사용

이 접근 방식의 기본 아이디어는 입력 문자열을 문자별로 반복하고 길이가 m인 각 하위 문자열이 교체하려는 하위 문자열과 일치하는지 확인하는 것입니다. 그렇다면 교체 하위 문자열을 결과에 추가하고 포인터를 m 문자만큼 앞으로 이동합니다. 일치하지 않으면 현재 문자를 결과에 추가하고 포인터를 한 문자씩 앞으로 이동합니다.

파이썬3




def> replace_substring(test_str, s1, s2):> > # Initialize an empty string to store the result> > result> => ''> > # Initialize a variable to keep track of our position in the string> > i> => 0> > # Loop through the string one character at a time> > while> i <> len> (test_str):> > # Check if the current substring matches the substring we want to replace> > if> test_str[i:i> +> len> (s1)]> => => s1:> > # If it does, add the replacement substring to the result and move the pointer forward> > result> +> => s2> > i> +> => len> (s1)> > else> :> > # If it doesn't, add the current character to the result and move the pointer forward> > result> +> => test_str[i]> > i> +> => 1> > # Return the final result> > return> result> # test> test_str> => 'geeksforgeeks'> s1> => 'geeks'> s2> => 'abcd'> print> (replace_substring(test_str, s1, s2))>

산출

abcdforabcd 

시간 복잡도: O(nm), 여기서 n은 입력 문자열의 길이이고 m은 대체될 ​​하위 문자열의 길이입니다.
보조 공간: O(n), 결과를 저장할 새 문자열을 생성하기 때문입니다.