从此行中提取 a 值
Extract the a value from this line
我知道这已经被问过很多次了,但我正在努力提取波纹管的中间部分
id1=({'children': '', 'edgeParameter': 1.0, 'id': 8, 'isOutOfDate': False, 'name': 'Datum pt-5', 'parents': '1&', 'path': 'unknown', 'sketch': 'unknown'})
我试图得到的结果是身份证号码。在这种情况下 8.
output= 8
有什么想法吗?
字典周围的括号在未明确转换为元组时不起作用。尝试例如将 print type((1))
与打印 print type((1, ))
进行比较。然后只需使用字典索引。 print id1['id']
。这确实是最基本的 python,所以如果这给您带来了问题,请学习基本的 python 课程,例如在 coursera.
如果您发布的字面意思是 python str
,并且它始终包含括号和其中的单个字典表示形式,包含键 'id',那么一个非常简单的方法是围绕 'id.
的相应值对字符串进行切片
id1 = "({'children': '', 'edgeParameter': 1.0, 'id': 8, 'isOutOfDate': False, 'name': 'Datum pt-5', 'parents': '1&', 'path': 'unknown', 'sketch': 'unknown'})"
output = id1.split("'id':")[1].split(',')[0]
这本身就是一个字符串,包括任何前缀或尾随空格。如果您知道这始终是一个整数,请执行 output = int(output)
。分解:
id1.split("'id':") # creates a list with two elements: everything up until 'id' and everything after it
id1.split("'id':")[1] # selects everything after 'id', the first thing being the desired value
id1.split("'id':")[1].split(',') # breaks THAT string up where there are commas since the value ends with a comma.
id1.split("'id':")[1].split(',')[0] # selects the value
也可以使用 eval
代替上述方法,但总是不鼓励这样做!
我知道这已经被问过很多次了,但我正在努力提取波纹管的中间部分
id1=({'children': '', 'edgeParameter': 1.0, 'id': 8, 'isOutOfDate': False, 'name': 'Datum pt-5', 'parents': '1&', 'path': 'unknown', 'sketch': 'unknown'})
我试图得到的结果是身份证号码。在这种情况下 8.
output= 8
有什么想法吗?
字典周围的括号在未明确转换为元组时不起作用。尝试例如将 print type((1))
与打印 print type((1, ))
进行比较。然后只需使用字典索引。 print id1['id']
。这确实是最基本的 python,所以如果这给您带来了问题,请学习基本的 python 课程,例如在 coursera.
如果您发布的字面意思是 python str
,并且它始终包含括号和其中的单个字典表示形式,包含键 'id',那么一个非常简单的方法是围绕 'id.
id1 = "({'children': '', 'edgeParameter': 1.0, 'id': 8, 'isOutOfDate': False, 'name': 'Datum pt-5', 'parents': '1&', 'path': 'unknown', 'sketch': 'unknown'})"
output = id1.split("'id':")[1].split(',')[0]
这本身就是一个字符串,包括任何前缀或尾随空格。如果您知道这始终是一个整数,请执行 output = int(output)
。分解:
id1.split("'id':") # creates a list with two elements: everything up until 'id' and everything after it
id1.split("'id':")[1] # selects everything after 'id', the first thing being the desired value
id1.split("'id':")[1].split(',') # breaks THAT string up where there are commas since the value ends with a comma.
id1.split("'id':")[1].split(',')[0] # selects the value
也可以使用 eval
代替上述方法,但总是不鼓励这样做!