简体   繁体   English

从给定的已找到子字符串中删除字符串字符,直到Python结束

[英]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' 什么是从'in'一词中删除所有字符串内容直到结尾的pythonic方法,留下这样的字符串:'blah blah blah blah'

Using split(" in ") , you can split the string from the "in". 使用split(" in ") ,您可以从“in”中拆分字符串。

This produces a list with the two ends. 这会生成一个包含两端的列表。 Now take the first part by using [0]: 现在使用[0]来获取第一部分:

string.split(" in ")[0]

If you don't want the space character at the end, then use rstrip(): string.split(" in ")[0].rstip() 如果你不想在结尾处使用空格字符,那么使用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. 如果基本单位是字符,请使用str.partition

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 strip()移除之前的空间in

I don't know whether you call it pythonic or not. 我不知道你是否称它为pythonic。 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM