2011-07-01 93 views
1

我用Python寫一個程序,並且有一定的問題(我是100%的新的Python):的Python:正則表達式和字符串長度的字節

import re 

rawData = '7I+8I-7I-9I-8I-' 

print len(rawData) 

rawData = re.sub("[0-9]I\+","",rawData) 
rawData = re.sub("[0-9]I\-","",rawData) 

print rawData 
  1. 如何使用2正則表達式合併成一個|?這意味着它將只使用一個正則表達式操作來擺脫9I-9I+
  2. len(rawData)返回rawData的長度是字節嗎?

謝謝。

+4

就這麼簡單' 「[0-9] I [+ - ]」' –

+0

的Python 2.x或Python 3中? –

+0

在Python 2.x中,rawData只是一些字節,但在Python 3中它將是Unicode文本。 –

回答

5

看到區別:

$ python3 
Python 3.1.3 (r313:86834, May 20 2011, 06:10:42) 
[GCC 4.4.5] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> len('día') # Unicode text 
3 
>>> 

$ python 
Python 2.7.1 (r271:86832, May 20 2011, 17:19:04) 
[GCC 4.4.5] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> len('día') # bytes 
4 
>>> len(u'día') # Unicode text 
3 
>>> 


Python 3.1.3 (r313:86834, May 20 2011, 06:10:42) 
[GCC 4.4.5] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> len(b'día') 
    File "<stdin>", line 1 
SyntaxError: bytes can only contain ASCII literal characters. 
>>> len(b'dia') 
3 
>>> 
+0

哇。我從來不知道:(我在服務器上使用python 2.6.5。 –

+0

那麼你如何在python 3中獲得字節的len?是否有一種通用的方式獲取字符串的長度在Python 2和Python中的字節長度3? –

+1

在Python 3中,如果你想要字節,你必須使用b'bytes' –

0

len引用應用於unicode字符串時的字符數(這是微妙的,其他答案會更清楚地說明),編碼字符串中的字節,列表中的項目(或集合中的項目或字典中的鍵) ...

rawData = re.sub("[0-9]I(\+|-)","",rawData) 
+0

一個字符是1個字節嗎? –

+0

我建議你閱讀這篇文章:http://www.joelonsoftware.com/articles/Unicode.html – MRAB

+0

@MRAB我讀過它了。作爲F.C.放它'len('día')'在Python 3中是3是3,而在Python 2中是4。我主要使用Python 3。 「編碼」並沒有提及unicode(在那裏使用了錯誤的詞),我指的是諸如'\ x03'之類的字符串。雖然可能長度爲4,但只有1的長度(因爲打印時只有一個字符) – cwallenpoole

相關問題