开发者

Removing the first part of a concatenated string with Python

I have a string as follows

CompilationStatistics_Compilation_StepList_Map_TimingUsage_ClockList_Clock_MinimumPeriod

What would be the simplest way to remove the first part (CompilationStatistics_) or the last part (_MiniumuPeriod)?开发者_JAVA百科

I think about using regular expression, but I expect there should a better way.

m = re.search("{.+}_{.+}", string)
m.group(2)


See the Python documentation for String methods, particularly partition and rpartition:

s = "CompilationStatistics_Compilation_StepList_Map_TimingUsage_ClockList_Clock_MinimumPeriod"
print s.partition('_')[2].rpartition('_')[0]

Result

Compilation_StepList_Map_TimingUsage_ClockList_Clock


'_'.join(s.split("_")[1:-1])?

Changing the splice numbers will change how much you get: removing the "-1" will only remove the first item, for example.


All but first:

s[s.find('_') + 1:]

All but last:

s[0:s.rfind('_')]

Without either:

s[s.find('_') + 1:s.rfind('_')]

find returns the first index of the string, and rfind returns the last. Then, we just use slice syntax.


If you know the size of the chunks you want to cut out, you can use Python's string slicing, like this:

s="CompilationStatistics_Compilation_StepList_Map_TimingUsage_ClockList_Clock_MinimumPeriod"
print s[22:-14]

Of course, there are other ways you can find the number you need, like using String.rindex() to find the place where the end chunk you want to cut off starts. For example:

print s[len("CompilationStatistics_"):s.rindex("_MinimumPeriod")]


Removing the first part is trivially down with split():

s.split("_", 1)[1] # Take the second part of the string, split into 2 pieces.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜