从python中的一行中拉出特定的子字符串 [英] Pull a specific substring out of a line in python

查看:149
本文介绍了从python中的一行中拉出特定的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其中的许多行格式如下:

I have a file with many lines formatted as such:

DIV ID=0X78800009 EXT="LOS ANGELES" TY=STANDARD OWN=0X74400002 ABBR=LA

我需要提取EXT值,但只提取引号中的部分.我目前正在使用这个:

I need to pull out the EXT value, but only the part in quotes. I'm currently using this:

for line in file:
    if sub in line:
        extlist.append([item[4:] for item in line.split() if item.startswith('EXT=')].pop())

但是它仅将LOS ANGELES的"LOS"部分附加到idlist中.我是python的新手,但是有一种方法可以将item[4:]包装在str(item[4:])中并使用

But it only appends the "LOS" part of LOS ANGELES to idlist. I'm a little new to python, but is there a way to wrap item[4:] in str(item[4:]) and use string functions to extract the value i need?

请注意,EXT字段中的文本长度不同,它们都是随机的城市名称.

As a note, the text in the EXT field varies in length, they are all random city names.

推荐答案

如果可以确保您的行中没有其他双引号,则此简单方法将起作用:

If you can be sure that there are no other double quotes in your line then this simple approach will work:

s='DIV ID=0X78800009 EXT="LOS ANGELES" TY=STANDARD OWN=0X74400002 ABBR=LA'

s.split('"')[1]
'LOS ANGELES'

请注意,使用 正则表达式 更灵活/如果不满足上述约束条件,则可以找到一种可靠的方法.

Note that using a regular expression is a more flexible/robust way to find this if the above constraints don't hold.

否则,这是按照简单胜于复杂"的精神解决此问题的一种方法.(Python的禅宗).

Otherwise this is one way to solve this problem in the spirit of "Simple is better than complex." (The Zen of Python).

这篇关于从python中的一行中拉出特定的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆