从字符串中提取值的更好方法

时间:2010-12-09 11:30:43

标签: python

str = 'This is first line \n 2 line start from her\ Service Name: test \n some 4 line \n User Name: amit \n some something \n Last Name: amit amit \n

基本上我感兴趣的是获取服务名称和用户名。 我应该使用正则表达式来执行此操作。 我想创建一个类似

的字典
dict['service_name'] = 'test'
dict['user_name'] = 'amit'
dict['last_name'] = 'amit amit'

那么搜索和获取值的最佳方式是什么。

由于

2 个答案:

答案 0 :(得分:5)

假设:

str = 'This is first line \n 2 line start from her\nService Name: test \n some 4 line \nUser Name: amit \n some something \nLast Name: amit amit \n'

以下代码:

dict([line.split(':') for line in str.split('\n') if ':' in line])

产生

{'Last Name': ' amit amit ', 'Service Name': ' test ', 'User Name': ' amit '}

您可能希望将split(':')更改为split(':', 1),以避免右侧冒号出现问题。此外,如果空格有问题,您可能需要向strip进行一些调用。

答案 1 :(得分:0)

它不是很优雅,但你可以使用'Service Name:'作为分隔符将字符串分解为数组。