[英]Remove string characters from a given found substring until the end in Python
我有以下字符串:在罗斯托克,等等等等等等
什么是从'in'一词中删除所有字符串内容直到结尾的pythonic方法,留下这样的字符串:'blah blah blah blah'
使用split(" in ")
,您可以从“in”中拆分字符串。
这会生成一个包含两端的列表。 现在使用[0]来获取第一部分:
string.split(" in ")[0]
如果你不想在结尾处使用空格字符,那么使用rstrip(): string.split(" in ")[0].rstip()
欢迎。
如果基本单位是单词,请使用正则表达式。
import re
line = 'justin in Rostock'
print(re.split(r'\bin\b', line, maxsplit=1)[0].strip())
贾斯汀
如果基本单位是字符,请使用str.partition
。
line = 'blah blah blah blah in Rostock'
new_string = line.partition('in')[0].strip()
print(new_string)
等等等等
strip()
移除之前的空间in
我不知道你是否称它为pythonic。 至少它似乎做了这个工作。
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.