python - How to remove everything before certain character in Python
问题描述
I'm new to python and struggle with a certain task:
I have a String that could have anything in it, but it always "ends" the same. It can be just a Filename, a complete path, or just a random string, ending with a Version Number.
Example:
C:\Users\abc\Desktop\string-anotherstring-15.1R7-S8.1
string-anotherstring-15.1R7-S8.1
string-anotherstring.andanother-15.1R7-S8.1
What always is the same (looking from the end) is that if you reach the second dot and go 2 characters in front of it, you always match the part that I'm interested in. Cutting everything after a certain string was "easy," and I solved it myself - that's why the string ends with the version now :)
Is there a way to tell python, "look for the second dot from behind the string and go 2 in front of it and delete everything in front of that so that I get the Version as a string?
Happy for any pointers in the right direction.
Thanks
解决方案
If you want the version number, can you use the hyphen (-) to split the string? Or do you need to depend on the dots only?
Please see below use of rsplit and join which can help you.
>>> a = 'string-anotherstring.andanother-15.1R7-S8.1'
>>> a.rsplit('-')
['string', 'anotherstring.andanother', '15.1R7', 'S8.1']
>>> a.rsplit('-')[-2:] #Get everything from second last to the end
['15.1R7', 'S8.1']
>>> '-'.join(a.rsplit('-')[-2:]) #Get everything from second last to the end, and join them with a hyphen
'15.1R7-S8.1'
>>>
For using dots, use the same way
>>> a
'string-anotherstring.andanother-15.1R7-S8.1'
>>> data = a.rsplit('.')
>>> [data[-3][-2:]]
['15']
>>> [data[-3][-2:]] + data[-2:]
['15', '1R7-S8', '1']
>>> '.'.join([data[-3][-2:]] + data[-2:])
'15.1R7-S8.1'
>>>
推荐阅读
- powershell - 具有不同信息的两个对象
- git - 将带有大文件的 GitLab 存储库迁移到 GitHub,同时维护两个上游
- pyspark - 如何修改多个案例的列数据。(对于 pyspark)
- haskell - 从括号之间提取文本
- python - 如何检查子进程的输出但也隐藏它?
- reactjs - 'ReactComponent' 不是从 svg 导出的
- python - 使用python在崇高文本中出现文件路径错误
- windows - 跟踪日志,直到给定的表达式与 Docker 匹配
- javascript - 如何在函数后编码'('时关闭VS Code上的Intellisense自动完成功能
- reactjs - 动态按钮创建 React