top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration
Print Preview

spilt a string in python

+1 vote
75 views

I want to split a string so that I always return everything BEFORE the LAST underscore

HELLO_xxxxxxxx.lst # should return HELLO
HELLO_GOODBYE_xxxxxxxx.ls # should return HELLO_GOODBYE

I have tried with rsplit but cannot get it to work.

posted May 16, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

3 Answers

0 votes

str.split takes a limit argument. Try your_string.split(_, 1)

answer May 16, 2013 by anonymous
0 votes

mystr.rsplit("_",1)[0]

answer May 16, 2013 by anonymous
0 votes

.rsplit takes an optional "how many splits do you want?" parameter that defaults to giving you all of them. Just ask for one right-most split:

 TESTS = [
   ("HELLO_xxxxxxx.lst", "HELLO"),
   ("HELLO_GOODBYE_xxxxx.ls", "HELLO_GOODBYE"),
 ]

 for input, expected in TESTS:
 result = input.rsplit('_', 1)[0]
 if result == expected:
 verdict = "passed"
 else:
 verdict = "failed"
 print "%r -> %r == %r (%s)" % (input, result, expected, verdict,)
answer May 16, 2013 by anonymous
Similar Questions
+2 votes

I have a multi-line string and I need to remove the very first line from it. How can I do that? I looked at StringIO but I can't seem to figure out how to properly use it to remove the first line.

+4 votes

Probably I'm turning the use of regular expressions upside down with this question. I don't want to write a regex that matches prefixes of other strings, I know how to do that. I want to generate a regex -- given another regex --, that matches all possible strings that are a prefix of a string that matches the given regex.

E.g. You have the regex ^[a-z]*4R$ then the strings "a", "ab", "A4" "ab4" are prefixes of this regex (because there is a way of adding characters that causes the regex to match), but "4a" or "a44" or not.
How do I programmatically create a regex that matches "a", "ab", "A4", etc.. but not "4a", "a44", etc..

Logically, I'd think it should be possible by running the input string against the state machine that the given regex describes, and if at some point all the input characters are consumed, it's a match. (We don't have to run the regex until the end.) But I cannot find any library that does it...


Useful Links with Similar Problem
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#470/147, 3rd Floor, 5th Main,
HSR Layout Sector 7,
Bangalore - 560102,
Karnataka INDIA.
QUERY HOME
...