User2939
User2939

Reputation: 165

Get a substring from each text line

I have a text file with following lines:

User Input: "Hello"...................<1sec> 
User Input: "Hi!".....................<2sec>
User Input: "How's it going"..........<1sec>

I just want the strings in the ""

for now I am using,

m= ""
for line in file:
     if "USER INPUT" in lines :
         m+=line[12:]

I am not sure as to how to get the position of " to make sure its only between the two "".

Upvotes: 2

Views: 124

Answers (3)

Gigaflop
Gigaflop

Reputation: 390

You can split the lines on the " character to get a list of all elements on any side of said character. IDLE example:

>>> s = """User Input: "Hello"...................<1sec> 
User Input: "Hi!".....................<2sec>
User Input: "How's it going"..........<1sec>"""

>>> for line in s.splitlines():
    try:
        print(line.split('"')[1])
    except IndexError:
        pass


Hello
Hi!
How's it going

Upvotes: 1

Waleed Iqbal
Waleed Iqbal

Reputation: 106

Another approach using findall:

import re

s = """User Input: "Hello"...................<1sec> 
User Input: "Hi!".....................<2sec>
User Input: "How's it going"..........<1sec>"""

for line in s.splitlines():

  output = re.findall(r'"([^"]*)"', line)
  if output:
    print(output[0])

Output:

Hello
Hi!
How's it going

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

Using Regex.

Ex:

import re
s = """User Input: "Hello"...................<1sec> 
User Input: "Hi!".....................<2sec>
User Input: "How's it going"..........<1sec>"""

for line in s.splitlines():
    if "User Input:" in line:
        m = re.search(r'\"(?P<data>.*?)\"', line)     #Get content between ""
        if m:
            print(m.group("data"))

Output:

Hello
Hi!
How's it going

Upvotes: 5

Related Questions