Line = "A[0x04] Va [0xf]
如何將這些線條拆分爲兩個變量,分別爲0x04
和0xf
?優雅的方式去掉括號中的值在Python中
嘗試的解決方案:
for line in sys.stdin:
line.strip("[]").split
Line = "A[0x04] Va [0xf]
如何將這些線條拆分爲兩個變量,分別爲0x04
和0xf
?優雅的方式去掉括號中的值在Python中
嘗試的解決方案:
for line in sys.stdin:
line.strip("[]").split
使用列表理解:
>>> Line = "A[0x04] Va [0xf]"
>>> [x.partition(']')[0] for x in Line.split('[') if ']' in x]
['0x04', '0xf']
我會用re.findall
:
>>> from re import findall
>>> Line = "A[0x04] Va [0xf] "
>>> findall("\[([^\]]*)\]", Line)
['0x04', '0xf']
>>> x,y = findall("\[([^\]]*)\]", Line)
>>> x
'0x04'
>>> y
'0xf'
>>>
下面是正則表達式模式的崩潰:
\[ # [
([^\]]*) # Capture group to get zero or more characters that are not ]
\] # ]
In [36]: %paste
answer = []
take = False
line = "A[0x04] Va [0xf] "
start = 0
for i,char in enumerate(line):
if not take:
if char == '[' :
take = True
start = i+1
else:
if char == ']':
take = False
answer.append(line[start:i])
## -- End pasted text --
In [37]: answer
Out[37]: ['0x04', '0xf']
+1沒有正則表達式 –
工程,但我很難找到它的優雅。不必要的正則表達式很好避免,但在這種情況下,它可能是正確工作的正確工具。 –
我在這裏:-) –
缺少C/C++的的sscanf()函數在另一方面,不使用變量名首都。見PEP 8:http://www.python.org/dev/peps/pep-0008/ –