简体   繁体   中英

How to extract just the first line of multiline string

I am using split() to parse till a colon. I have several colons in my text but I just need the string from the first line. What i need to do to just get the first line?

line = """Hello : 
          This is a test ......:

          Testpath: C:\\...
          blablablabla
          123:"""

if ' :' in line: 
  av = line.split(" :",1)[0]
  print av

Is it possible to access the first line without using regexpression??

If I understood your question correctly, you want to print only the first line of the multi-lined string irrespective of colon as separator. If this is the case, here is my possible solution (for windows os):

line = """ bravo cos
        daring in the blah blah."""

The soln is:

print(line.split("\n")[0])

Hope it helps.

If you just want the first line you might want to use splitlines

If I understood well your question, this code might help you.

line = """Hello : 
      This is a test ......:

      Testpath: C:\\...
      blablablabla
      123:"""

first, *others = line.splitlines()

first will contain the first line, others will contian a list of other lines

NB: You are not using any regex

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