在一些char之后替换字符串

时间:2014-02-21 12:03:57

标签: python string

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

string1/aaa
this is string2/bbb
string 3/ccc
this is some string/ddd

我想在“/”之后读取子串。我需要这个输出:

aaa
bbb
ccc
ddd

谢谢。

2 个答案:

答案 0 :(得分:6)

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

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']

答案 1 :(得分:0)

使用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']
>>>