简体   繁体   中英

Find the number of \n before a given word in a long string

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):

在此处输入图片说明

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: 在此处输入图片说明

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 ?

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM