如何在某个字符串后剥离所有内容

时间:2015-04-15 15:37:14

标签: python strip

基本上我想转这样的东西

FlorenceBuilding04_geometry_clean_001_Loc1_position

/root/world/geo/FlorenceBuilding04_model_geometry

FlorenceBuilding05_geometry1_clean_001_Loc1_position

/root/world/geo/FlorenceBuilding05_model_geometry

代码:

s = GetName()
if s.endswith( "_position" ):
    rootname = "/root/world/geo/"+s[ :- 18 ].rstrip("_")
    rootname =rootname.replace("geometry","model_geometry")

提前致谢

2 个答案:

答案 0 :(得分:2)

你也可以这样做:

>>> a = 'FlorenceBuilding04_geometry_clean_001_Loc1_position'
>>> path = '/root/world/geo/' + a.split('geometry')[0] + 'model_geometry'
>>> print(path)
/root/world/geo/FlorenceBuilding04_model_geometry

答案 1 :(得分:1)

您对标准并不十分具体,但似乎您希望将第一部分保持为“_geometry”并丢弃其他内容。使用index

即可轻松完成
>>> def convert(example):
...     print "/root/world/geo/%s_model_geometry" % example[:example.find("_geometry")]
... 
>>> convert("FlorenceBuilding04_geometry_clean_001_Loc1_position")
/root/world/geo/FlorenceBuilding04_model_geometry
>>> convert("FlorenceBuilding05_geometry1_clean_001_Loc1_position")
/root/world/geo/FlorenceBuilding05_model_geometry