为了账号安全,请及时绑定邮箱和手机立即绑定

如何删除python中特定字符之后的所有字符?

如何删除python中特定字符之后的所有字符?

互换的青春 2019-10-17 10:33:47
我有一个字符串。如何删除某个字符后的所有文本?(在这种情况下...)之后的文本将...更改,所以这就是为什么我要删除某个字符之后的所有字符的原因。
查看完整描述

3 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

假设分隔符为“ ...”,但它可以是任何字符串。


text = 'some string... this part will be removed.'

head, sep, tail = text.partition('...')


>>> print head

some string

如果找不到分隔符,head将包含所有原始字符串。


分区功能是在Python 2.5中添加的。


分区(...)S.partition(sep)->(head,sep,tail)


Searches for the separator sep in S, and returns the part before it,

the separator itself, and the part after it.  If the separator is not

found, returns S and two empty strings.


查看完整回答
反对 回复 2019-10-17
?
慕村225694

TA贡献1880条经验 获得超4个赞

如果要删除字符串中最后一次出现分隔符之后的所有内容,我会发现这很有效:


<separator>.join(string_to_split.split(<separator>)[:-1])


例如,如果  string_to_split是像一个路径root/location/child/too_far.exe,你只需要在文件夹路径,您可以通过拆分"/".join(string_to_split.split("/")[:-1]),你就会得到 root/location/child


查看完整回答
反对 回复 2019-10-17
  • 3 回答
  • 0 关注
  • 9015 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信