python - 查找长字符串中给定单词之前的\n 数量

标签 python string pandas

我有一个很长的字符串:

string = 'Idnum\rId\nkey: maturity\n2\nmaturity\rpara1\rpara2\n1Y\r0\r0\n2Y\r0\r0'

现在我想找出单词 \nmaturity 之前的 \n 的数量(在字符串中是唯一的,我们可以看到答案是 2)。

这是这个问题的动机,如果你听不懂我下面说的,就忽略它,专注于上面的问题。

我想使用pandas读取data(我不确定data的结构,可能是csv):

enter image description here

并使用语法:

value = pandas.read_csv(data, sep = '\t', skiprows = 3).set_index('maturity') 

到期之前跳过前3行以获得如下表: enter image description here

所以我需要找出maturity的行号来确定我应该跳过多少行。但我只知道数据

data.getvalue() = 'Idnum\rId\nkey: maturity\n2\nmaturity\rpara1\rpara2\n1Y\r0\r0\n2Y\r0\r0'

(\n 正在更改行,\r 正在更改单元格)。所以我必须天真地找到maturity之前的\n的数量来确定原表中maturity的行号(或数据)。

那么,如果您熟悉上述结构,您能告诉我如何在data中查找maturity的行号吗?

最佳答案

一种方法:

  • 首先使用“\nmaturity”作为分隔符分割字符串,并获取第一个(即第一个找到的项目的左侧)。
  • 然后使用 count 来计算 '\n' 的数量。

未经测试:

string = 'Idnum\rId\nkey: maturity\n2\nmaturity\rpara1\rpara2\n1Y\r0\r0\n2Y\r0\r0'
stringUntilMaturity = string.split('\nmaturity')[0]
counts = stringUntilMaturity.count('\n')

关于python - 查找长字符串中给定单词之前的\n 数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54292729/

相关文章:

c++ - QStringList 去除字符串中的空格

java - 让 Java 在字母之后对符号进行排序(就像 Linux 排序一样)

python - Pandas :groupby索引然后使用函数填充数据框

python - 根据另一列中的相应行使用条件值填充数据帧的列的最佳方法是什么?

python - 如何生成所有可能的二元 nxn 矩阵,其中每行的总和为 1

python - 如何将字典转换为嵌套字典?

python - 如何检查用户输入是否为 float

python - 导入错误: cannot import name Serializer

python - 重新计算循环内的字符串长度

python - 通过从不同的数据框中查找来替换列中的 Pandas 值