简体   繁体   中英

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 ?

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

You can use re module. 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:

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

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM