split twice in the same expression?
Imagine I have the following:
inFile = "/adda/adas/sdas/hello.txt" # that instruction give me hello.txt Name = inFile.name.split("/") [-1] # that one give me the name I want - just hello Name1 = Name.split(".") 
Is there any chance to simplify that doing the same job in just one expression?
Asked by: Lyndon224 | Posted: 06-12-2021
from os.path import basename, splitext pathname = "/adda/adas/sdas/hello.txt" name, extension = splitext(basename(pathname)) print name # --> "hello"
Using os.path.basename and os.path.splitext instead of str.split, or re.split is more proper (and therefore received more points then any other answer) because it does not break down on other platforms that use different path separators (you would be surprised how varried this can be).
It also carries most points because it answers your question for "one line" precisely and is aesthetically more pleasing then your example (even though that is debatable as are all questions of taste)Answered by: Emma261 | Posted: 07-01-2022
Answering the question in the topic rather than trying to analyze the example...
You really want to use Florians solution if you want to split paths, but if you promise not to use this for path parsing...
You can use re.split() to split using several separators by or:ing them with a '|', have a look at this:
Answered by: Wilson546 | Posted: 07-01-2022
import re inFile = "/adda/adas/sdas/hello.txt" print re.split('\.|/', inFile)[-2]
Answered by: Eric822 | Posted: 07-01-2022
>>> inFile = "/adda/adas/sdas/hello.txt" >>> inFile.split('/')[-1] 'hello.txt' >>> inFile.split('/')[-1].split('.') 'hello'
if it is always going to be a path like the above you can use os.path.split and os.path.splitext
The following example will print just the hello
from os.path import split, splitext path = "/adda/adas/sdas/hello.txt" print splitext(split(path))
For more info see https://docs.python.org/library/os.path.htmlAnswered by: Sam738 | Posted: 07-01-2022
I'm pretty sure some Regex-Ninja*, would give you a more or less sane way to do that (or as I now see others have posted: ways to write two expressions on one line...)
But I'm wondering why you want to do split it with just one expression? For such a simple split, it's probably faster to do two than to create some advanced either-or logic. If you split twice it's safer too:
I guess you want to separate the path, the file name and the file extension, if you split on '/' first you know the filename should be in the last array index, then you can try to split just the last index to see if you can find the file extension or not. Then you don't need to care if ther is dots in the path names.
*(Any sane users of regular expressions, should not be offended. ;)Answered by: Thomas171 | Posted: 07-01-2022
Split a list with regex expression in python
I'm trying to split a string using regex expression but I struggle to be efficient with it My input is a string as a list with each line being an element of the list. Some lines in the list are dates with always the same format which is Weekday, Month Number, Year. An example can be Wednesday, March 16, 2022or Friday, April 8, 2022 and then the next elements in the list ...
Python idiom for '... if ... else ...' expression
How to write the expression shorter: return '%.0f' % float_var if float_var else float_var or if float_var: return formatted_string else: return None Thanks!
python - How can I use Perl's s/// in an expression?
I got a headache looking for this: How do you use s/// in an expression as opposed to an assignment. To clarify what I mean, I'm looking for a perl equivalent of python's re.sub(...) when used in the following context: newstring = re.sub('ab', 'cd', oldstring) The only way I know how to do this in perl so far is: $oldstring =~ s/ab/cd/; $newstring = $oldstr...
python - about the return expression
level: beginner the following code will print 'False' def function(x): if len(x) == 5: return True else: return x == x[-1] print function('annb') why does the line "else: return x == x[-1]" print False? i do understand what's happening but i'm having difficulties to put this into plain english...how can this behaviour be described? is this a commonly / often ...
python - how to write a regex for this expression?
url1 = http://xyz.com/abc url2 = http://xyz.com//abc I want to write a regex that validate both url1 and url2
What is an expression in Python?
I have some confusion about its meaning or definition. Isn't that some code that produce or calculate new data values? (Says Zelle in his book) Then I wonder if a string data type is an expression. If it is, then what does eval() do when its argument is a string? The book by Zelle sayseval(<string>) evaluates string as an expression, what does th...
regex - Find expression in python
String example: 'file_name.c: 120' or 'file_name.m: 312' Target: find exactly '.c:' or '.m:' using regular expression. Since it's confusing issue, I would to get a good tutorial for regular expression if someone knows. Ron.
"self" in python lambda expression
def buildTestCase(xmlfile, description, method, evalString): func = lambda self, xmlfile=xmlfile, method=method, evalString=evalString: \ method(self, evalString, feedparser.parse(xmlfile)) func.__doc__ = description return func Above is a code snippet from feedparser, why there is a "self" in function definition method(self, evalString, feedparser.parse(xmlfile))? Thanks.
python list expression
Say I got a string: s = '''1 2 3 4 5 6 7 8 9 ''' I want to turn each line of string s into a list of floating-point value, that is: l = [[1.0 2.0 3.0], [4.0 5.0 6.0], [7.0 8.0 9.0]] How can I do this in one line?
python - SymPy: How to get values from expression
I am trying to write a simple SymPy function. a = Wild('a') b = Wild('b') p = Wild('p') q = Wild('q') ... if (U).match(b/(a+s)): return b*exp(-a*t) Lets say that U = 3/(7+s). I would like my result to be 3*exp(-7*t), but it just returns b*exp(-a*t). Is there a way to get those values and assign them to a and b?
regex - How to match a space at the beginning of the expression python?
I have the following String "Sample" however in some occurences there may be one or more spaces in the beginning: " Sample" or " Sample" Without using trim, what regular expression can I use to match if there is one? I am using (\s+) for the current String. I want the space to be included as part of the same one group.
python - Regular expression to match start of filename and filename extension
What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'? The regular expression should match any of the following: RunFoo.py RunBar.py Run42.py It should not match: myRunFoo.py RunBar.py1 Run42.txt The SQL equivalent of what I am looking for is ... LIKE 'Run%.py' ...
regex - python regular expression to split paragraphs
How would one write a regular expression to use in python to split paragraphs? A paragraph is defined by 2 linebreaks (\n). But one can have any amount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph. I am using python so the solution can use python's regular expression syntax whi...
python - Problem with Boolean Expression with a string value from a lIst
I have the following problem: # line is a line from a file that contains ["baa","beee","0"] line = TcsLine.split(",") NumPFCs = eval(line) if NumPFCs==0: print line I want to print all the lines from the file if the second position of the list has a value == 0. I print the lines but after that the following happens: Traceback (most recent call last): ['baaa'...
python - Regular expression to extract URL from an HTML link
I’m a newbie in Python. I’m learning regexes, but I need help here. Here comes the HTML source: <a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a> I’m trying to code a tool that only prints out http://ptop.se. Can you help me please?
regex - How can I translate the following filename to a regular expression in Python?
I am battling regular expressions now as I type. I would like to determine a pattern for the following example file: b410cv11_test.ext. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance.
python - What is the regular expression for the "root" of a website in django?
I'm using django and when users go to www.website.com/ I want to point them to the index view. Right now I'm doing this: (r'^$', 'ideas.idea.views.index'), However, it's not working. I'm assuming my regular expression is wrong. Can anyone help me out? I've looked at python regular expressions but they didn't help me.
regex - Python Regular Expression to add links to urls
I'm trying to make a regular expression that will correctly capture URLs, including ones that are wrapped in parenthesis as in (http://example.com) and spoken about on coding horror at https://blog.codinghorror.com/the-problem-with-urls/ I'm currently using the foll...
python - Regular expression to detect semi-colon terminated C++ for & while loops
In my Python application, I need to write a regular expression that matches a C++ for or while loop that has been terminated with a semi-colon (;). For example, it should match this: for (int i = 0; i < 10; i++); ... but not this: for (int i = 0; i < 10; i++) This looks trivial at first glance, until you realise...
regex - How do i write a regular expression for the following pattern in python?
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign Case 1: str1=str2 Case 2: str1 = str2 please note there can be a space or none between the either side of the "=" sign Mine is like this, but only works for one of the cases! m=re...
regex - Why is the regular expression returning an error in python?
Am trying the following regular expression in python but it returns an error import re ... #read a line from a file to variable line # loking for the pattern 'WORD' in the line ... m=re.search('(?<=[WORD])\w+',str(line)) m.group(0) i get the following error: AttributeError: 'NoneType' object has no attribute 'group'