2014-01-24 4 views
1
여기

는 파이썬의 문자열입니다파이썬 함수 인수 및 문서 혼란

a = "asdf as df adsf as df asdf asd f" 

내가 || ""와 ""모두 교체 할 말 있습니다, 그래서 수행

>>> a.replace(" ", "||") 
'asdf||as||df||adsf||as||df||asdf||asd||f' 

string.replace(s, old, new[, maxreplace]) 
    Return a copy of string s with all occurrences... 

나는 다큐를 기반으로 s을 "생략"할 수 있지만, 나의 혼란은 다음과 the documentation에서 정보입니다 mentement 내가 필요합니다 s; 단, oldnew 만 제공합니다. 나는 파이썬 문서가 많이있는 것을 보았다. 나는 무엇을 놓치고 있습니까?

답변

1

방법의 최초의 파라미터가 수정되고 (self 보통 불림) 객체에 대한 참조하고 object.method(...) 표기법을 사용할 때 암시 전달된다. 그래서이 :

a = "asdf as df adsf as df asdf asd f" 
print a.replace(" ", "||") 

이하는 것과 같습니다

a = "asdf as df adsf as df asdf asd f" 
print str.replace(a, " ", "||") 

stra 객체의 클래스되고. 그것은 단지 구문 설탕입니다.

1

개체의 메서드를 호출하면 개체가 첫 번째 매개 변수로 자동 제공됩니다. 일반적으로이 방법에서는 self이라고합니다.

string.replace(s, old, new) 

를하거나 객체의 메소드를 호출 할 수 있습니다 :

그래서 당신은 객체를 전달 함수를 호출 할 수

s.replace(old, new) 

모두 기능적으로 동일합니다.

+0

'string '이 아니라'str'입니다. –

5

모듈 기능이 stringstr 개체 메서드를 혼합합니다. 당신이 언급하는

문서는 3 소요 replace라는 문자열 모듈에서 함수가, 실제로 string module documentation. (또는 선택적 4) 인수 :

In [9]: string 
Out[9]: <module 'string' from '/usr/lib/python2.7/string.pyc'> 

In [11]: string.replace(a, ' ', '||') 
Out[11]: 'asdf||as||df||adsf||as||df||asdf||asd||f' 

astr 객체입니다 - (strstring는 모듈이다 일종)

In [15]: type(a) 
Out[15]: str 

str 그리고 개체가 replace 방법이있다. str 방법에 대한 설명서는 here입니다.

+1

'string' 모듈은 대부분의 기능이'str' 문자열 클래스와 합쳐 졌기 때문에 사용해서는 안된다고 덧붙일 것입니다. +1 –

+0

+1 그것을 못 박는 것에 +1! – tawmas

+0

@StefanoSanfilippo :'string '과 같은 일부 문자열 함수 (http://docs.python.org/2/library/string.html#deprecated-string-functions)가 있습니다.atof'이지만 전체 모듈은 더 이상 사용되지 않습니다. 함수는 특정'str'에 바인딩 된 메서드가 아니라 함수가 필요할 때 유용 할 수 있습니다. 상수 또한 유용합니다. – unutbu