我正在学习Python字符串操作并试图将分隔文本转换为变量。匹配多个字符串
即"On Tap: 20 | Bottles: 957 | Cans: 139"
此字符串应分配20的值,以抽头957到瓶,和139到罐。该字符串不固定,可能会有所不同(例如,3个值或0,Tap,Bottles或Can的位置也可以互换)。但是它不工作按我的预期,并重新分配瓶的每一次价值
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)
:
到目前为止,我已经开发了这一点。
输出:
['On Tap: 20 ', ' Bottles: 957 ', ' Cans: 139']
On Tap: 20
Found Bottles
20
Bottles: 957
Found Bottles
957
Cans: 139
Found Bottles
139
我已经包含了很多print
语句调试代码。我的目的只是为适当的变量赋值。
正如你正在尝试学习python并试图将字符串转换为变量,因此你的变量应该从字符串自动创建,而不是通过将匹配值赋值给你所渲染的变量。应该使用exec(就学习python而言) –
你能举个例子吗? –
看我的答案,我已经发布在这里 –