简体   繁体   中英

Remove string characters from a given found substring until the end in Python

I've got the following string: blah blah blah blah in Rostock

What's the pythonic way for removing all the string content from the word 'in' until the end, leaving the string like this: 'blah blah blah blah'

Using split(" in ") , you can split the string from the "in".

This produces a list with the two ends. Now take the first part by using [0]:

string.split(" in ")[0]

If you don't want the space character at the end, then use rstrip(): string.split(" in ")[0].rstip()

Welcome.

Use regular expression if the base unit is word.

import re
line = 'justin in Rostock'
print(re.split(r'\bin\b', line, maxsplit=1)[0].strip())

justin

example in regular expression

Use str.partition if the base unit is character.

line = 'blah blah blah blah in Rostock'
new_string = line.partition('in')[0].strip()

print(new_string)

blah blah blah blah

strip() removes the space before in

I don't know whether you call it pythonic or not. At least it seems to do the job.

def getNameAndCity(nameWithCity: str) -> (str, str):
    if not " in " in nameWithCity:
        return nameWithCity, None
    pieces = nameWithCity.split(" in ")
    name = " in ".join(pieces[0:-1])
    return name, pieces[-1]

# No 'in' at all
assert ("Michael",None) == getNameAndCity("Michael")
# Nothing special
assert ("Johan", "Oslo") == getNameAndCity("Johan in Oslo")
# "'in' in City
assert ("Sandra", "Berlin") == getNameAndCity("Sandra in Berlin")
# 'in' in Name and City
assert ("Christine", "Berlin") == getNameAndCity("Christine in Berlin")
# 'in' as an extra token
assert ("Christine in Love", "Berlin") == getNameAndCity("Christine in Love in Berlin")
s = "Ahe, Christiane Dr. von der Praxis für Kieferorthopädie in Rostock"
if " in " in s:
    s = s[:s.find(" in ")]
# Else leave the string untouched.

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