【问题标题】:Parsing a string in python without knowing is in the string在python中解析字符串而不知道在字符串中
【发布时间】:2013-04-18 20:18:08
【问题描述】:

我正在尝试解析一组引号之间的随机字符串。 数据始终采用以下形式:

klheafoiehaiofa"randomtextnamehere.ext"fiojeaiof;jidoa;jfioda

我知道 .ext 是什么,我想要的是 randomtextnamehere.ext,而且它总是用 " " 分隔。

目前我只能处理某些情况,但我希望能够处理任何情况,如果我可以从第一个“开始抓住第二个”,那就太好了。因为每行可能有不止一组 "。

谢谢!

【问题讨论】:

  • 还有...到目前为止,您在代码中为解决问题写了什么?

标签: python string parsing quotes


【解决方案1】:

你可以使用str.split方法:

Docstring:
S.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string S, using sep as the
delimiter string.  If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.

In [1]: s = 'klheafoiehaiofa"randomtextnamehere.ext"fiojeaiof;jidoa;jfioda'

In [2]: s.split('"', 2)[1]
Out[2]: 'randomtextnamehere.ext'

【讨论】:

  • 好。 split 的第二个参数在功能上不是必需的。
  • @wim -- 你当然是对的,我试图证明你可以在分隔符的前两次出现显式拆分字符串only
猜你喜欢
  • 1970-01-01
  • 2011-06-20
  • 2013-09-01
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
相关资源
最近更新 更多