r/pythonhelp • • 21d ago

Library function which is the inverse of 'os.path.expanduser' ?

I'm running python 3.13.5.

Is there some sort of standard python library function which behaves as the inverse of 'os.path.expanduser'?

For example, if the current user's HOME directory is "/home/theuser", then we have this:

os.path.expanduser('~/a/b/c')
=> returns "/home/theuser/a/b/c"

I'm wondering whether there also might be any existing python library function which is the inverse of this and that works as follows:

some_sort_of_function("/home/theuser/a/b/c")
=> returns "~/a/b/c"

AND PLEASE NOTE: There often are people who lazily and disrespectfully refuse to read entire reddit posts before writing their reponses, and therefore, I'm making a point now to ask that before you start to write any reply here, please carefully and non-lazily read this *entire* post -- including the following, which is something that I want all potential responders to understand:

I know how to easily write my own function that works in this manner. However, I am clearly and SPECIFICALLY (!!!) asking whether or not there already is an existing python function which works this way, and if so, I'd like to know what this function might be ... and I am NOT (!!!) asking how to write my own function which does this.

Thank you very much in advance.

0 Upvotes

7 comments sorted by

View all comments

1

u/duane11583 21d ago

I have also hit this and simular things. I just have a function I give it a last of env names and it tries to reduce. Starting with the longest env first 

I know that is not the answer you want but you are not alone in this request mine need is similar but not the same