2012-10-06 23 views
3

所以標題解釋了它的大部分。我開始研究Objective-C for iOS,並且我還沒有發現是否有方法使用translate() - 就像在Objective C中一樣。如何在Python中使用目標c中的str.translate()方法?

這是我在Python中它:程序

#!/usr/bin/python 

from string import maketrans # Required to call maketrans function. 

intab = "aeiou" 
outtab = "12345" 
trantab = maketrans(intab, outtab) 

str = "this is string example....wow!!!"; 
print str.translate(trantab); 

輸出:

th3s 3S str3ng 2x1mpl2 .... w4w!

+1

'str'是Python中的內建名稱;不要覆蓋它。 – jfs

+0

他的例子直接來自這裏:http://www.tutorialspoint.com/python/string_translate.htm。我也假設他知道它是基於標題內置的。 – OozeMeister

回答

1

就我而言,像translate()沒有內置方法。 (然而,通過使用PyObjc,你可以在Objective C中得到完全相同的功能,查看它)

你可以嘗試在一個NSMutableString上用replaceOccurrencesOfString:withString:options:range做一些事情或者自己寫一個函數,用一個循環來查看每個字符在字符串中,檢查它是否必須被替換,如果是,則用正確的字符替換它。 (因爲那是translate()功能做什麼,對不對?)

+1

[我已經發布了'translate()'的算法](http://stackoverflow.com/a/12764045/4279)來說明它的功能。 – jfs

0

translates()的算法(就地變體)在純C是:

char *input; // input C string 

for (char *s = input; *s; ++s) 
    *s = trantab[(unsigned char) *s]; 

其中trantab可以從intab製成,outtab

char trantab[256]; // translation table 
for (int i = 0; i < 256; ++i) 
    trantab[i] = i; // initialize 

while (*intab && *outtab) 
    trantab[(unsigned char) *intab++] = *outtab++;