0

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

3
  • s.replace("/pic", "") Commented Jun 15, 2017 at 5:06
  • Just to be clear, do you want to remove the part starts with slash until a dot or is it always /pic? Commented Jun 15, 2017 at 5:06
  • I added an edit Commented Jun 15, 2017 at 5:09

3 Answers 3

2

You can use re module. Try -

import re
a = 'foldername/pic.jpg'
out = re.sub(r'/.*\.', r'.', a)
print(out)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.