2017-03-10 3 views
2

(S.replace(old, new[, count]) -> str)에서 'aaa'.replace('a','b') 대신 str.replace('a','b','l')을 사용하면 'a'가 반환됩니다.Python의 str.replace가 예외를 throw하지 않음

정수 대신 'l'이 읽히지 않는다고 상상해보십시오. 일치하는 항목이 없기 때문에 'a'를 반환하고 예외를 throw하지 않는 이유는 무엇입니까?

답변

4

str.replace('a','b','l')'a'.replace('b','l')으로 해석됩니다.

당신은 클래스 strmethod를 호출하고 여기에 명시 적으로 인스턴스 'a' 전달되고 있습니다

str.replace('a', ...) -> 'a'.replace(...) 

대신 암시 'a'.replace(...)를 통해 인스턴스를 전달하는 전통적인 방법을 가고. 따라서 'b''l'str.replace에 대한 oldnew 인수로 해석됩니다.

str.replacecount의 값으로 비 INT를 제공하는 경우 당신은 당신의 예외를 얻을 것이다 :.

str.replace('a', 'a', 'b', '1') 

TypeErrorTraceback (most recent call last) 
<ipython-input-23-f8b6e2752fe6> in <module>() 
----> 1 str.replace('a', 'a', 'b', '2') 

TypeError: 'str' object cannot be interpreted as an integer 
+0

'A'의 경우를, (...) 대체 str.replace 것보다 더 나쁜 (...) 다음과 같은 맥심 : '암시 적보다 낫다'. –

관련 문제