Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

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'

like image 343
Ian Spitz Avatar asked Jan 30 '18 18:01

Ian Spitz


3 Answers

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.

like image 179
Suraj Kothari Avatar answered Nov 03 '22 19:11

Suraj Kothari


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

like image 24
Aaron Avatar answered Nov 03 '22 18:11

Aaron


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")
like image 20
Thomas Weller Avatar answered Nov 03 '22 19:11

Thomas Weller