Python 替换字符后的字符串

Python 替换字符后的字符串,python,string,Python,String,如何替换字符串中的子字符串?例如,我有字符串: string1/aaa this is string2/bbb string 3/ccc this is some string/ddd 我想读“/”后面的子字符串。我需要这个输出: aaa bbb ccc ddd 谢谢。您可以拆分字符串以获取数据 my_string.split("/")[1] 比如说, data = ["string1/aaa", "this is string2/bbb", "string 3/ccc",

如何替换字符串中的子字符串?例如,我有字符串:

string1/aaa
this is string2/bbb
string 3/ccc
this is some string/ddd
我想读“/”后面的子字符串。我需要这个输出:

aaa
bbb
ccc
ddd

谢谢。

您可以拆分字符串以获取数据

my_string.split("/")[1]
比如说,

data = ["string1/aaa", "this is string2/bbb", "string 3/ccc",
        "this is some string/ddd"]    
print [item.split("/")[1] for item in data]
输出

['aaa', 'bbb', 'ccc', 'ddd']
使用re:

>>> data = """string1/aaa
... this is string2/bbb
... string 3/ccc
... this is some string/ddd"""
>>>
>>> import re
>>> re.findall('.*?\/(\w+)', data)
['aaa', 'bbb', 'ccc', 'ddd']
>>>

让我们注意到,当以常量字符串split()进行拆分就足够了,并且您不需要正则表达式的机制,这会导致额外的开销。是的,我明白,我只是展示了一种方法,他并没有要求使用最有效的方法。无论如何,谢谢你的建议。当然!我只是觉得在你的答案上加一个脚注会很有用。