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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With