我正在学习 Python 字符串操作并尝试将分隔文本转换为变量。
即“点击:20 | 瓶子:957 | jar 头:139”
此字符串应为 Tap 分配值 20,为 Bottles 分配 957,为 Cans 分配 139。此字符串不固定,可能会有所不同(例如 3 个值或 0,Tap、Bottles 或 Cans 的位置也可以互换)。
到目前为止,我已经开发了这个:
import re
strEx = "On Tap: 20 | Bottles: 957 | Cans: 139"
barServingText = strEx.split('|')
print(barServingText)
for i in barServingText:
print (i)
if i.find("Bottles"):
print("Found Bottles")
Bottles = re.sub('[^0-9]*','',i)
print(Bottles)
elif i.find("Cans"):
print("Found Cans")
Cans = re.sub('[^0-9]*','',i)
print(Cans)
elif i.find("Tap"):
print("Found Tap")
Tap = re.sub('[^0-9]*','',i)
print(Tap)
但是它并没有按照我的预期工作,并且每次都重新分配 Bottles 的值。
输出:
['On Tap: 20 ', ' Bottles: 957 ', ' Cans: 139']
On Tap: 20
Found Bottles
20
Bottles: 957
Found Bottles
957
Cans: 139
Found Bottles
139
我包含了许多 print
语句来调试代码。我的目的只是为适当的变量赋值。
最佳答案
find
在找不到字符串时返回 -1
并且 -1
被视为 True
( bool(-1)
给出 True
) 所以你必须使用 find(...) != -1
import re
strEx = "On Tap: 20 | Bottles: 957 | Cans: 139"
barServingText = strEx.split('|')
print(barServingText)
for i in barServingText:
print (i)
if i.find("Bottles") != -1:
print("Found Bottles")
Bottles = re.sub('[^0-9]*','',i)
print(Bottles)
elif i.find("Cans") != -1:
print("Found Cans")
Cans = re.sub('[^0-9]*','',i)
print(Cans)
elif i.find("Tap") != -1:
print("Found Tap")
Tap = re.sub('[^0-9]*','',i)
print(Tap)
顺便说一句:对于您的数据,您不需要re
。您可以使用split
(和strip
)
Bottles = i.split(':')[1].strip()
Cans = i.split(':')[1].strip()
Tap = i.split(':')[1].strip()
关于python - 匹配多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39815214/