문자열은 텍스트/문자를 나타내는 데 사용되는 데이터 유형입니다. 이 기사에서는 i 제거 문제에 대한 다양한 방법을 제시합니다.일문자열의 문자를 추출하고 Python을 사용하여 이를 달성하는 데 사용할 수 있는 가능한 솔루션에 대해 이야기합니다.
Input: 'Geeks123For123Geeks' Output: GeeksForGeeks Explanation: In This, we have removed the '123' character from a string.>
Python의 문자열에서 문자 제거
다음은 문자열에서 문자를 제거할 수 있는 방법입니다. 파이썬 :
- 사용 str.replace()
- 사용 번역하다()
- 사용 재귀
- 네이티브 방법 사용
- 슬라이스 + 연결 사용
- 사용 str.join()
- 사용 bytearray
- 사용 접두어 제거 ()
교체()를 사용하여 문자열에서 문자 제거
str.replace() 원하는 문자의 모든 항목을 바꾸는 데 사용할 수 있습니다. 특정 인덱스를 빈 문자로 대체하여 문제를 해결할 수 있으므로 문자열에서 문자 제거 작업을 수행하는 데에도 사용할 수 있습니다.
파이썬3
# Initializing String> test_str>=> 'GeeksForGeeks'> # Removing char at pos 3> # using replace> new_str>=> test_str.replace(>'e'>, '')> # Printing string after removal> # removes all occurrences of 'e'> print>(>'The string after removal of i'th character( doesn't work) : '> +> new_str)> # Removing 1st occurrence of s, i.e 5th pos.> # if we wish to remove it.> new_str>=> test_str.replace(>'s'>, '',>1>)> # Printing string after removal> # removes first occurrences of s> print>(>'The string after removal of i'th character(works) : '> +> new_str)> |
>
ddl 대 dml
>산출
The string after removal of i'th character( doesn't work) : GksForGks The string after removal of i'th character(works) : GeekForGeeks>
시간 복잡도: 에)
공간 복잡도: 에)
약점: replacement() 사용의 주요 단점은 pos의 char과 일치하는 문자열에 중복이 있는 경우 실패한다는 것입니다. 나. replacement()는 특정 문자의 모든 발생을 대체하므로 pos i에 있는 모든 문자의 발생을 모두 대체합니다. 대체 문자가 1에 대해 발생하면 때때로 이 기능을 사용할 수 있습니다.성문자열의 시간.
Translate()를 사용하여 문자열에서 특정 문자 제거
이 방법은 문자열에서 문자를 제거하는 강력한 메커니즘을 제공합니다. 이 방법에서는 다음을 사용하여 techcodeview.com에서 123을 제거했습니다. 문자열.번역() .
파이썬3
str> => 'Geeks123For123Geeks'> > print>(>str>.translate({>ord>(i):>None> for> i>in> '123'>}))> |
>
>
산출
GeeksForGeeks>
시간 복잡도: 에)
공간 복잡도: 오(m)
재귀를 사용하여 문자열에서 특정 문자 제거
재귀를 사용하여 문자열에서 i번째 문자를 제거하려면 제거할 문자열과 인덱스를 인수로 사용하는 재귀 함수를 정의할 수 있습니다. 이 함수는 인덱스가 0인지 확인합니다. 이 경우 첫 번째 문자가 제거된 문자열을 반환합니다. 인덱스가 0이 아닌 경우 함수는 인덱스가 1 감소한 문자열에 대해 함수를 다시 호출한 결과와 연결된 문자열의 첫 번째 문자를 반환할 수 있습니다.
파이썬3
def> remove_ith_character(s, i):> ># Base case: if index is 0,> ># return string with first character removed> >if> i>=>=> 0>:> >return> s[>1>:]> ># Recursive case: return first character> ># concatenated with result of calling function> ># on string with index decremented by 1> >return> s[>0>]>+> remove_ith_character(s[>1>:], i>-> 1>)> # Test the function> test_str>=> 'GeeksForGeeks'> new_str>=> remove_ith_character(test_str,>2>)> print>(>'The string after removal of ith character:'>, new_str)> # This code is contributed by Edula Vinay Kumar Reddy> |
>
>
산출
The string after removal of ith character: GeksForGeeks>
시간 복잡도: 에)
공간 복잡도: 에)
기본 방법을 사용하여 문자열에서 문자 제거
이 방법에서는 다음을 실행하면 됩니다. 파이썬 루프 문자가 오면 추가하고 인덱스가 i인 경우를 제외하고 기존 문자열에서 새 문자열을 만듭니다.
파이썬3
test_str>=> 'GeeksForGeeks'> # Removing char at pos 3> new_str>=> ''> for> i>in> range>(>len>(test_str)):> >if> i !>=> 2>:> >new_str>=> new_str>+> test_str[i]> # Printing string after removal> print> (>'The string after removal of i'th character : '> +> new_str)> |
>
>산출
The string after removal of i'th character : GeksForGeeks>
시간 복잡도: 에)
공간 복잡도: O(n), 여기서 n은 문자열의 길이입니다.
나는 제거일슬라이스를 사용하여 문자열의 문자
하나는 사용할 수 있습니다 스트링 슬라이스 pos i 앞에서 문자열을 자르고 pos i 뒤에서 슬라이싱합니다. 그런 다음 사용하여 문자열 연결 둘 다, 나는일문자가 문자열에서 삭제된 것처럼 보일 수 있습니다.
파이썬3
# Initializing String> test_str>=> 'GeeksForGeeks'> # Removing char at pos 3> # using slice + concatenation> new_str>=> test_str[:>2>]>+> test_str[>3>:]> # Printing string after removal> # removes ele. at 3rd index> print> (>'The string after removal of i'th character : '> +> new_str)> |
100만 개 중 10개
>
>산출
The string after removal of i'th character : GeksForGeeks>
시간 복잡도: 에)
공간 복잡도: 에)
나는 제거일다음을 사용하여 문자열의 문자 str.join()
이 방법에서는 문자열의 각 요소를 먼저 목록의 각 요소로 변환한 다음 각 요소를 결합하여 지정된 인덱스를 제외한 문자열을 형성합니다.
파이썬3
# Initializing String> test_str>=> 'GeeksForGeeks'> # Removing char at pos 3> # using join() + list comprehension> new_str>=> ''.join([test_str[i]>for> i>in> range>(>len>(test_str))>if> i !>=> 2>])> # Printing string after removal> # removes ele. at 3rd index> print> (>'The string after removal of i'th character : '> +> new_str)> |
>
>산출
The string after removal of i'th character : GeksForGeeks>
시간 복잡도: 에)
공간 복잡도: 에)
bytearray를 사용하여 Python의 문자열에서 문자 삭제
문자열 s와 정수 i를 입력으로 사용하는 Remove_char(s, i) 함수를 정의합니다. 그런 다음 bytearray(s, 'utf-8')를 사용하여 입력 문자열 s를 bytearray로 변환합니다. i번째 요소를 삭제합니다. bytearray del b[i]를 사용합니다. b.decode()를 사용하여 수정된 bytearray를 다시 문자열로 변환하고 수정된 문자열을 반환합니다.
파이썬3
def> remove_char(s, i):> >b>=> bytearray(s,>'utf-8'>)> >del> b[i]> >return> b.decode()> # Example usage> s>=> 'hello world'> i>=> 4> s>=> remove_char(s, i)> print>(s)> |
>
>
산출
hell world>
시간 복잡도: 에)
공간 복잡도: 에)
Removeprefix()를 사용하여 문자열에서 문자 제거
접두어 제거() 접두사를 제거하고 문자열의 나머지 부분을 반환합니다. 제거하려는 문자가 두 파티션 중 하나의 접두사에 오도록 문자열을 두 부분으로 나누어 특정 인덱스에 대한 문자열에서 문자를 제거한 다음 문자를 제거하는 방법을 적용할 수 있습니다.
파이썬3
러드야드 키플링의 말을 바꿔서 말해보세요
#initializing the string> s>=>'techcodeview.com'> #if you wanted to remove 'G' of 0th index> s1>=>s.removeprefix(>'G'>)> #if you wanted to remove 'f'> s2>=>s[:>5>]>+>s[>5>:].removeprefix(>'f'>)> print>(s1)> print>(s2)> |
>
>
산출:
eeksforGeeks GeeksorGeeks>
시간 복잡도: 에)
공간 복잡도: 에)