简体   繁体   English

如何在Python中删除以某些字符开头和结尾的子字符串

[英]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.

相关问题 查找所有以特定字符开头和结尾的子字符串 - find all substring that starts and ends with specific characters Python正则表达式如何删除以 - 开头并以逗号结尾的句子末尾的字符串? - Python regex how to remove string at the end of sentence that starts with - and ends with a comma? 电子邮件提取以不需要的字符开始和结束(python) - Email extraction starts and ends with unwanted characters (python) python:如何删除某些字符 - python: how to remove certain characters 如何从 python 中的字符串中删除某些 substring? - how to remove certain substring from string in python? Python 正则表达式如何找到以给定单词开头并以两个单词之一结尾的 substring - Python regex how to find a substring that starts with a given word and ends with either of two words 在以 python 中的特定字符开头和结尾的字符串中查找并打印 substring 的索引 - Find and print the indexes of a substring in string that starts and ends with a specific character in python 提取以符号开头和结尾的子字符串并替换为 Python 中的变量 - Extract substring that starts and ends with symbol and replace with variable in Python 如何删除 python 中以某些字符结尾的行? - How to remove lines end with certain characters in python? 如何从字符串中删除某些字符? [蟒蛇] - How to remove certain characters from a string? [Python]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM