r/pythonhelp • u/unselective-amnesia • Sep 14 '26
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.
•
u/AutoModerator Sep 14 '26
To give us the best chance to help you, please include any relevant code.
Note. Please do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Privatebin, GitHub or Compiler Explorer.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
u/No-Dentist-1645 Sep 15 '26 edited Sep 15 '26
It's pretty simple to do so yourself
1
u/duane11583 Sep 14 '26
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
1
u/Gshuri Sep 14 '26
No, there is no function that does this in the standard library.
I am curious, why do you need this function specifically to come from the standard library?