2012-11-18 116 views
1

我想按以下方式拆分字符串。下面是一個簡單的字符串:試圖用Python將字符串拆分爲多個部分

"Hello this is a string.-2.34 This is an example1 string." 

請注意,「」是一個U + F8FF Unicode字符和字符串類型是Unicode。

我想打破字符串:

"Hello this is a string.","-2.34"," This is an example1 string." 

我已經寫了一個正則表達式來分割字符串,但使用這個我不能得到我想要的數字部分。 (在第一串-2.34)

我的代碼:

import re 
import os 
from django.utils.encoding import smart_str, smart_unicode 

text = open(r"C:\data.txt").read() 
text = text.decode('utf-8') 
print(smart_str(text)) 

pat = re.compile(u"\uf8ff-*\d+\.*\d+") 
newpart = pat.split(text) 
firstpart = newpart[::1] 

print ("first part of the string ----") 
for f in firstpart: 
f = smart_str(f) 
print ("-----") 
print f 

回答

5

如果你想保持它的re.split結果你需要把周圍-*\d+\.*\d+括號:

import re 
text = u"Hello this is a string.\uf8ff-2.34 This is an example1 string." 
print(re.split(u'\uf8ff(-*\d+\.*\d+)', text)) 

產量

[u'Hello this is a string.', u'-2.34', u' This is an example1 string.'] 
+0

T非常感謝!這工作。 :) – Ans

相關問題