파이썬에서 문자열의 모든 문자 인스턴스를 삭제하는 방법은 무엇입니까?
이 문자열에서 문자의 모든 인스턴스를 어떻게 삭제합니까? 내 코드는 다음과 같습니다.
def findreplace(char, string):
place = string.index(char)
string[place] = ''
return string
그러나 이것을 실행하면 다음과 같은 일이 발생합니다.
>>> findreplace('i', 'it is icy')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in findreplace
TypeError: 'str' object does not support item assignment
왜 이런거야?
파이썬에서 문자열은 불변입니다. 즉, 일단 문자열이 생성되면 문자열의 내용을 변경할 수 없습니다. 변경해야하는 경우 변경 사항과 함께 문자열의 새 인스턴스가 생성됩니다.
이를 염두에두고이 문제를 해결할 수있는 많은 방법이 있습니다.
사용하여
str.replace,>>> "it is icy".replace("i", "") 't s cy'사용하여
str.translate,>>> "it is icy".translate(None, "i") 't s cy'정규식 사용,
>>> import re >>> re.sub(r'i', "", "it is icy") 't s cy'이해력을 필터로 사용하여
>>> "".join([char for char in "it is icy" if char != "i"]) 't s cy'filter기능 사용>>> "".join(filter(lambda char: char != "i", "it is icy")) 't s cy'
타이밍 비교
def findreplace(m_string, char):
m_string = list(m_string)
for k in m_string:
if k == char:
del(m_string[m_string.index(k)])
return "".join(m_string)
def replace(m_string, char):
return m_string.replace("i", "")
def translate(m_string, char):
return m_string.translate(None, "i")
from timeit import timeit
print timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
print timeit("replace('it is icy','i')", "from __main__ import replace")
print timeit("translate('it is icy','i')", "from __main__ import translate")
결과
1.64474582672
0.29278588295
0.311302900314
str.replace및 str.translate방법은 허용되는 답변보다 8 배 및 5 배 빠릅니다.
Note: Comprehension method and filter methods are expected to be slower, for this case, since they have to create list and then they have to be traversed again to construct a string. And re is a bit overkill for a single character replacement. So, they all are excluded from the timing comparison.
Try str.replace():
str="it is icy"
print str.replace("i", "")
>>> x = 'it is icy'.replace('i', '', 1)
>>> x
't is icy'
Since your code would only replace the first instance, I assumed that's what you wanted. If you want to replace them all, leave off the 1 argument.
Since you cannot replace the character in the string itself, you have to reassign it back to the variable. (Essentially, you have to update the reference instead of modifying the string.)
replace() method will work for this. Here is the code that will help to remove character from string. lets say
j_word = 'Stringtoremove'
word = 'String'
for letter in word:
if j_word.find(letter) == -1:
continue
else:
# remove matched character
j_word = j_word.replace(letter, '', 1)
#Output
j_word = "toremove"
I suggest split (not saying that the other answers are invalid, this is just another way to do it):
def findreplace(char, string):
return ''.join(string.split(char))
Splitting by a character removes all the characters and turns it into a list. Then we join the list with the join function. You can see the ipython console test below
In[112]: findreplace('i', 'it is icy')
Out[112]: 't s cy'
And the speed...
In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
Out[114]: 0.9927914671134204
Not as fast as replace or translate, but ok.
# s1 == source string
# char == find this character
# repl == replace with this character
def findreplace(s1, char, repl):
s1 = s1.replace(char, repl)
return s1
# find each 'i' in the string and replace with a 'u'
print findreplace('it is icy', 'i', 'u')
# output
''' ut us ucy '''
ReferenceURL : https://stackoverflow.com/questions/22187233/how-to-delete-all-instances-of-a-character-in-a-string-in-python
'Program Club' 카테고리의 다른 글
| styles.xml과 themes.xml의 차이점은 무엇입니까? (0) | 2020.12.15 |
|---|---|
| 파일 대화 상자 열기, 여러 Excel 확장에 대해 하나의 필터? (0) | 2020.12.15 |
| Python : Pandas 데이터 프레임의 두 열 (변수)을 기반으로 빈도 수를 가져옵니다. (0) | 2020.12.15 |
| 생성자의 C ++ 가상 함수 (0) | 2020.12.15 |
| 현재 Magento 사용자입니까? (0) | 2020.12.14 |