2016-09-06 34 views
2

我們可以通過IronPython的定製一個.net應用程序(2.7.5版本)的Python返回字符串既海峽和unicode類型

這裏是腳本代碼:

stringToPlay = # get it from our .NET app interface toward python here. The method returns .NET string 

Log.Write("isinstance(stringToPlay, unicode): ", str(isinstance(stringToPlay, unicode))) 

Log.Write("isinstance(stringToPlay, str): ", str(isinstance(stringToPlay, str))) 

兩個日誌行將返回True?

stringToPlay值是「Ћирилица」。

當str和unicode應該是兩個獨立的類都從basestring繼承時,這怎麼可能?

謝謝

+0

什麼是類型(stringToPlay)的結果?你的'.net字符串'是'System.String'? –

回答

4

IronPython中,該str類型和unicode類型是相同的對象。 .NET字符串類型是unicode。

6

IronPython在strunicode之間沒有區別,如果您習慣於CPython 2語義,這可能會非常混亂。實際上,basestringunicode都是str的別名。

IronPython 2.7.4 (2.7.0.40) on .NET 4.0.30319.42000 (32-bit) 
Type "help", "copyright", "credits" or "license" for more information. 
>>> unicode 
<type 'str'> 
>>> basestring 
<type 'str'> 

關於字符串,IronPython的(2.X)表現得更像Python 3,用有點惱人的事實,你不能unicodestr之間如果要解碼編碼的基礎的類型區分/(和因爲它仍然是Python 2,所以也沒有bytes)。

+0

Unify和IronPython有什麼問題,CPython 2. *的方式,還是您列出的細節? –

+0

你的意思是Unicode,不是Unify,對不對? Python 2和Unicode的「問題」是字符串最初只是編碼的字節字符串(ASCII,Latin1,UTF-8或其他)。 'unicode'類型(代表與編碼無關的字符串)的引入會導致混淆,因爲現在您有兩種具有複雜關係的字符串類型。尤其是調用'encode' /'decode'無論類型是否有問題(例如,編碼已編碼的字符串,解碼unicode字符串等) –

+0

經驗法則:處理IronPython中的所有字符串,如unicode字符串。除非你在做IO,否則不要在字符串上調用'decode'或'encode'。那麼你應該沒有問題。 (這實際上是模仿Python 3字符串處理風格)。 –

相關問題