better way of extracting values from string
str =开发者_如何学JAVA '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
Basically What I am interested is getting the service name and user name. Should I user regular expression for doing this. I want to create a dict like
dict['service_name'] = 'test'
dict['user_name'] = 'amit'
dict['last_name'] = 'amit amit'
So what the best way of searching and getting the values.
Thanks
Given:
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'
The following code:
dict([line.split(':') for line in str.split('\n') if ':' in line])
produces:
{'Last Name': ' amit amit ', 'Service Name': ' test ', 'User Name': ' amit '}
You may want to change split(':')
to split(':', 1)
to avoid issues with colons on the right-hand sides. Additionally, you may want to sprinkle a few calls to strip
if whitespaces are an issue.
It isn't very elegnat, but you can explode() the string into an array using 'Service Name:' as the separator.
精彩评论