[英]How to remove a substring that starts and ends with certain characters in Python
I have a string like this 我有这样的字符串
foldername/pic.jpg
How can I remove this part /pic
so the new string will become foldername.jpg
? 如何删除/pic
这部分,使新字符串变为foldername.jpg
?
EDIT: I want to replace any string that starts with /
and end with .
编辑:我想替换以/
开头并以结束的任何字符串.
with a dot (.) so the new file name only contains the foldername.jpg 带有点(。),因此新文件名仅包含foldername.jpg
You can use re
module. 您可以使用re
模块。 Try - 尝试-
import re
a = 'foldername/pic.jpg'
out = re.sub(r'/.*\.', r'.', a)
print(out)
if that is all you have, you can do it like this: 如果仅此而已,则可以这样操作:
name = 'foldername/pic.jpg'
root = name.split('/')[0]
ext = name.split('.')[1]
name = root + ext
but if you are splitting file-paths, you will be better off with os.path
commands, for example: 但是,如果要分割文件路径,最好使用os.path
命令,例如:
import os
name = 'foldername/pic.jpg'
root = os.path.dirname(name)
_, ext = os.path.splitext(name)
name = root + '.' + ext
both cases return a string foldername.jpg
in these cases, but the os.path
commands are more flexible 在这两种情况下,这两种情况均返回字符串foldername.jpg
,但是os.path
命令更加灵活
For a more generic solution, try regular expressions. 有关更通用的解决方案,请尝试使用正则表达式。 In your specific example, I will make the assumption you want to remove a substring that starts with '/', and ends with 'c' (ie, /pic). 在您的特定示例中,我假设您要删除以'/'开头并以'c'结束(即/ pic)的子字符串。
In [394]: import re
In [395]: re.sub(r'(.+)\/\w+c(.+)', r'\1\2', 'foldername/pic.jpg')
Out[395]: 'foldername.jpg'
Just note that the second argument needs the raw string encapsulator r' ', if you want to interpolate variables, else the \\1 or \\2 have no effect. 只需注意第二个参数需要原始字符串封装器r'',如果要插入变量,则\\ 1或\\ 2无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.