Skip to content Skip to sidebar Skip to footer

How To Get Everything Before And Up To A Certain Substring Within A String?

How would I return a string up to a certain character? def get_header(s): '''(str) -> str Return the start of the given string upto and including .'''

Solution 1:

Your code should work, but won't include "</head>", so just add it at the end:

defget_header(s):
    '''(str) -> str
    Return the start of the given string upto and including
    </head>.'''return s.split('</head>')[0] + "</head>"

Solution 2:

This would be a fairly easy thing to do with Python's re module which matches a "regular expression" (or regex) to a string.

Here's how to use it to do what you want:

import re

defget_header(s):
    """(str) -> str
    Return the start of the given string upto and including </head>.
    """
    matches = re.search(r".*</head>", s)
    return matches.group(0) if matches elseNone

s = "hello python world </head> , i'm a beginner "print(get_header(s))  # -> hello python world </head>

Solution 3:

more_itertools is a third-party library that implements a split_after tool. Install via:

> pip install more_itertools

Given

import more_itertools as mits="hello python world </head> , i'm a beginner "

Code

pred = lambda x: x == "</head>"" ".join(next(mit.split_after(s.split(), pred)))
# 'hello python world </head>'

The string is split by spaces into "words". The full string is split after any words that suit the predicate. The first result is joined together.

Post a Comment for "How To Get Everything Before And Up To A Certain Substring Within A String?"