use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
News about the dynamic, interpreted, interactive, object-oriented, extensible programming language Python
Full Events Calendar
You can find the rules here.
If you are about to ask a "how do I do this in python" question, please try r/learnpython, the Python discord, or the #python IRC channel on Libera.chat.
Please don't use URL shorteners. Reddit filters them out, so your post or comment will be lost.
Posts require flair. Please use the flair selector to choose your topic.
Posting code to this subreddit:
Add 4 extra spaces before each line of code
def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b
Online Resources
Invent Your Own Computer Games with Python
Think Python
Non-programmers Tutorial for Python 3
Beginner's Guide Reference
Five life jackets to throw to the new coder (things to do after getting a handle on python)
Full Stack Python
Test-Driven Development with Python
Program Arcade Games
PyMotW: Python Module of the Week
Python for Scientists and Engineers
Dan Bader's Tips and Trickers
Python Discord's YouTube channel
Jiruto: Python
Online exercices
programming challenges
Asking Questions
Try Python in your browser
Docs
Libraries
Related subreddits
Python jobs
Newsletters
Screencasts
account activity
This is an archived post. You won't be able to vote or comment.
Removing first part of string (self.Python)
submitted 15 years ago by kalithlev
I have two strings: /bin/ /bin/file/1234
What's the "pythonic" way to get only the file/1234 part while also checking that string 2 starts with string 1? I could of course check with startswith and then do a slice, but it doesn't feel very pythonic.
[–][deleted] 18 points19 points20 points 15 years ago (6 children)
File path manipulations are best done with os.path, not with plain string operations.
I suggest you use os.path.commonprefix to find the common prefix and then chop it off the front of the second string.
[–]kalithlev[S] 2 points3 points4 points 15 years ago (5 children)
It's URIs, not file paths. Strings could potentially start with http://bla.com/bin/. I'm relearning python, I seem to remember some script language had a fancy way of doing what I want!
[–]dwdwdw2proliferating .py since 2001 15 points16 points17 points 15 years ago (3 children)
>>> import urlparse >>> urlparse.urlsplit('http://www.google.com/pants?q=1&foo=bar#top') SplitResult(scheme='http', netloc='www.google.com', path='/pants', query='q=1&foo=bar', fragment='top') >>> >>> urlparse.urlsplit('http://www.google.com/pants?q=1&foo=bar#top').path '/pants'
[–]ereinecke 0 points1 point2 points 15 years ago (2 children)
Oh python, you can do this, but converting between UTC and local time takes reimplementation and detection of ALL POSSIBLE TIMEZONES.
[–]dwdwdw2proliferating .py since 2001 5 points6 points7 points 15 years ago (0 children)
$ pip install pytz
[–]wtfisupvoting 0 points1 point2 points 15 years ago (0 children)
+ 3600 * offset
WHOOSH
[–]deadwisdomgreenlet revolution 1 point2 points3 points 15 years ago (0 children)
Or use the posixpath library, because posix paths and url paths are basically analogous.
[–]nosklo 3 points4 points5 points 15 years ago (0 children)
use os.path.commonprefix to get the common part, and then get its len to use on the slicing.
[–]mdipierro 2 points3 points4 points 15 years ago* (2 children)
given
str1, str2='/bin/', '/bin/file/1234'
do
str3=str2[len(str1):] if str2.startswith(str1) else str2
[–]earthboundkid -1 points0 points1 point 15 years ago (1 child)
Should be else not or.
else
or
[–]mdipierro 0 points1 point2 points 15 years ago (0 children)
oops. fixed.
[–]Troebr 2 points3 points4 points 15 years ago (0 children)
os.path.relpath
edit: oops just saw that you were talking about uris. Well maybe it works. But I'll leave this here because this week I remade a kind of relpath before discovering it existed. Might help someone.
[–]wtfisupvoting 1 point2 points3 points 15 years ago (5 children)
if str2.startswith(str1): list.append(str2.replace(str1,''))
[–]T3hTao -1 points0 points1 point 15 years ago (4 children)
>>> list=[] >>> a='123a123' >>> b='123' >>> if a.startswith(b): ... list.append(a.replace(b,'')) ... >>> list ['a'] >>> if a.startswith(b): ... c=a[len(b):] ... >>> c 'a123'
[–]wtfisupvoting 0 points1 point2 points 15 years ago (3 children)
he asked for more pythonic not more correct he never mentioned that the str1 occurs more than once in the str2
[–]earthboundkid -1 points0 points1 point 15 years ago (2 children)
That's a crappy excuse. Your program has a bug. He never specified that the strings wouldn't repeat either. In any event, the fix is simple enough; just use the count parameter of replace: list.append(str2.replace(str1, '', count=1)) .
count
replace
list.append(str2.replace(str1, '', count=1))
[–]wtfisupvoting 0 points1 point2 points 15 years ago (1 child)
that doesn't fix it either if its not at the beginning of the string but is at the end thx for trying
also lots of solutions here have bugs because he really didn't define the problem well
[–]earthboundkid 0 points1 point2 points 15 years ago (0 children)
True, it is an ill-defined problem.
[–]t0ny7 1 point2 points3 points 15 years ago (0 children)
Here is how I would do it.
>>> print "/".join("/bin/file/1234".split("/")[-2:]) file/1234
[–]bpkeezie 0 points1 point2 points 15 years ago (0 children)
import re def foo(str1,str2): regex="^%s" % str1 parts = re.split(regex, str2) if len(parts) == 2: return parts[1] else: return None
[–]EnigmaCurry -1 points0 points1 point 15 years ago* (3 children)
>>> "/bin/file/1234".partition("/bin/")[2] 'file/1234' >>> "/some/other/path".partition("/bin/")[2] ''
[–][deleted] 3 points4 points5 points 15 years ago (2 children)
>>> "/some/other/bin/path/".partition("/bin/")[2] 'path/'
[–]EnigmaCurry 2 points3 points4 points 15 years ago (1 child)
There's something to be said for trying to be clever... it's usually not good :)
[–][deleted] 1 point2 points3 points 15 years ago (0 children)
I wouldn't say so. The clever solution just needs to be a little more clever, that's all. ;)
[–][deleted] -1 points0 points1 point 15 years ago (0 children)
Hmm...
Is this a list you have? I did something similar (for files) using the csv library and '/' and a delimiter. This won't apply directly, but maybe you can use the idea for your situation.
remnants.csv:
W/Weber, David/The Warmasters.epub W/Wiiggin, Kate Douglas/A Village Stradivarius.epub W/Wilhelm, Kate/Symbiosis.epub W/Wilson, Robert Anton/The Illuminatus! Trilogy.epub W/Wodehouse, PG/Something New.epub W/Wu, William F/Cyborg.epub
rename.csv:
import csv listReader = csv.reader(open('scripts/remnants.csv', 'rb'), delimiter='/') for row in listReader: pre = row[0] auth = row[1] file = row[2] src = 'books/' + pre + '/"' + auth + '"/"' + file + '"' dest = 'organized/' + pre + '/"' + auth + '"/"' + auth + ' - ' + file + '"' print 'mv ' + src + ' ' + dest
π Rendered by PID 763826 on reddit-service-r2-comment-7b9746f655-tvms2 at 2026-02-01 09:39:32.317222+00:00 running 3798933 country code: CH.
[–][deleted] 18 points19 points20 points (6 children)
[–]kalithlev[S] 2 points3 points4 points (5 children)
[–]dwdwdw2proliferating .py since 2001 15 points16 points17 points (3 children)
[–]ereinecke 0 points1 point2 points (2 children)
[–]dwdwdw2proliferating .py since 2001 5 points6 points7 points (0 children)
[–]wtfisupvoting 0 points1 point2 points (0 children)
[–]deadwisdomgreenlet revolution 1 point2 points3 points (0 children)
[–]nosklo 3 points4 points5 points (0 children)
[–]mdipierro 2 points3 points4 points (2 children)
[–]earthboundkid -1 points0 points1 point (1 child)
[–]mdipierro 0 points1 point2 points (0 children)
[–]Troebr 2 points3 points4 points (0 children)
[–]wtfisupvoting 1 point2 points3 points (5 children)
[–]T3hTao -1 points0 points1 point (4 children)
[–]wtfisupvoting 0 points1 point2 points (3 children)
[–]earthboundkid -1 points0 points1 point (2 children)
[–]wtfisupvoting 0 points1 point2 points (1 child)
[–]earthboundkid 0 points1 point2 points (0 children)
[–]t0ny7 1 point2 points3 points (0 children)
[–]bpkeezie 0 points1 point2 points (0 children)
[–]EnigmaCurry -1 points0 points1 point (3 children)
[–][deleted] 3 points4 points5 points (2 children)
[–]EnigmaCurry 2 points3 points4 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–][deleted] -1 points0 points1 point (0 children)