Find the number of \n before a given word in a lon

2019-08-11 10:17发布

I have a long string:

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

Now I want to find out the number of \n before the word \nmaturity (is unique in the string and we can see the answer is 2).

Here is the motivation of this question, if you cannot understand what I say below, just ignore it and focus on the question above.

I want to use pandas to read the data (I am not sure for the structure of data, may be a csv):

enter image description here

and use the syntax:

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

to skip first 3 rows before maturity to obtain the table like: enter image description here

So I need to find out the row number of maturity to determine how many rows I should skip. But what I only know for data is

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

(\n is changing the line and \r is changing the cell). So I have to naively find the number of \n before maturity to determine the row number of maturity in the original table (or data).

So, if you are familiar with above structure, could you tell me how to find the row number of maturity in the data?

1条回答
时光不老,我们不散
2楼-- · 2019-08-11 10:46

One way to do it:

  • First split the string with '\nmaturity' as separator and take the first (thus left of the first found item).
  • Than use count to count the number of '\n's.

Untested:

string = 'Idnum\rId\nkey: maturity\n2\nmaturity\rpara1\rpara2\n1Y\r0\r0\n2Y\r0\r0'
stringUntilMaturity = string.split('\nmaturity')[0]
counts = stringUntilMaturity.count('\n')
查看更多
登录 后发表回答