Too much code - slicing

D

DataSmash

I need to create a simple utility to remove characters from either the
right or left side of directories.
This works, but there has to be a better way. I tried to use a
variable inside the brackets but I can't get
that to work. Can anyone think of a way to do this with less code?
Thanks!

import os

dirs = filter(os.path.isdir, os.listdir(''))
for dir in dirs:

# Left side
if num == '1' and side == "l":
code = dir[1:]
if num == '2' and side == "l":
code = dir[2:]
if num == '3' and side == "l":
code = dir[3:]
if num == '4' and side == "l":
code = dir[4:]
if num == '5' and side == "l":
code = dir[5:]
if num == '6' and side == "l":
code = dir[6:]
if num == '7' and side == "l":
code = dir[7:]
if num == '8' and side == "l":
code = dir[8:]
if num == '9' and side == "l":
code = dir[9:]
if num == '10' and side == "l":
code = dir[10:]
# Right side
if num == '1' and side == "r":
code = dir[:-1]
if num == '2' and side == "r":
code = dir[:-2]
if num == '3' and side == "r":
code = dir[:-3]
if num == '4' and side == "r":
code = dir[:-4]
if num == '5' and side == "r":
code = dir[:-5]
if num == '6' and side == "r":
code = dir[:-6]
if num == '7' and side == "r":
code = dir[:-7]
if num == '8' and side == "r":
code = dir[:-8]
if num == '9' and side == "r":
code = dir[:-9]
if num == '10' and side == "r":
code = dir[:-10]

print " Renaming "+dir+" to "+code
os.rename(dir, code)
 
B

Benjamin Kaplan

I need to create a simple utility to remove characters from either the
right or left side of directories.
This works, but there has to be a better way.  I tried to use a
variable inside the brackets but I can't get
that to work.  Can anyone think of a way to do this with less code?
Thanks!

import os

dirs = filter(os.path.isdir, os.listdir(''))
for dir in dirs:

   # Left side
<snip long if chain>

The int() type will convert a string to an int for you. So all you
need to do is check the side and slice accordingly.

if side=='l':
code = dir[int(num):]
else :
code = dir[:-1*int(num)]
 
A

AK

I need to create a simple utility to remove characters from either the
right or left side of directories.
This works, but there has to be a better way. I tried to use a
variable inside the brackets but I can't get
that to work. Can anyone think of a way to do this with less code?
Thanks!

import os

dirs = filter(os.path.isdir, os.listdir(''))
for dir in dirs:

# Left side
<snip long if chain>

The int() type will convert a string to an int for you. So all you
need to do is check the side and slice accordingly.

if side=='l':
code = dir[int(num):]
else :
code = dir[:-1*int(num)]

I also like this construct that works, I think, since 2.6:

code = dir[int(num):] if side == 'l' else dir[:-1*int(num)]

-ak
 
D

DataSmash

I need to create a simple utility to remove characters from either the
right or left side of directories.
This works, but there has to be a better way.  I tried to use a
variable inside the brackets but I can't get
that to work.  Can anyone think of a way to do this with less code?
Thanks!
import os
dirs = filter(os.path.isdir, os.listdir(''))
for dir in dirs:
   # Left side

<snip long if chain>

The int() type will convert a string to an int for you. So all you
need to do is check the side and slice accordingly.

if side=='l':
    code = dir[int(num):]
else :
    code = dir[:-1*int(num)]

Much appreciated!
I thought I tried every combination, guess I didn't try this as it
works great.
Thanks again.
 
A

Andreas Waldenburger

I also like this construct that works, I think, since 2.6:

code = dir[int(num):] if side == 'l' else dir[:-1*int(num)]
I wonder when this construct will finally start to look good.

/W
 
B

Bas

I also like this construct that works, I think, since 2.6:
code = dir[int(num):] if side == 'l' else dir[:-1*int(num)]

I wonder when this construct will finally start to look good.


Using IFs is just plain ugly. Why not go for the much more pythonic

code = (lambda s:dir[slice(*(s*int(num),None)[::s])])(cmp('o',side))

Much easier on the eyes and no code duplication ... ;)

Bas
 
S

Steven D'Aprano

I also like this construct that works, I think, since 2.6:

code = dir[int(num):] if side == 'l' else dir[:-1*int(num)]
I wonder when this construct will finally start to look good.


It looks good to me. It follows a common English idiom:

"What are you doing tonight?"
"I'll be going to the movies, if I finish work early, otherwise I'll stay
home and watch a DVD."
 
S

Seebs

I also like this construct that works, I think, since 2.6:
code = dir[int(num):] if side == 'l' else dir[:-1*int(num)]
I wonder when this construct will finally start to look good.
It looks good to me. It follows a common English idiom:
"What are you doing tonight?"
"I'll be going to the movies, if I finish work early, otherwise I'll stay
home and watch a DVD."

I hate that idiom in English, too. If you're going to give me a forking
conditional, I want to know about it early.

Basically, I can handle
do x if y
pretty well, but
do x if y else z
always breaks my parser.

So in English, I might say "I'll go to the store if I have time", but
I'd rarely use "I'll go to the store if I have time, otherwise I'll send
the house elf"; instead, I'd say "If I have time, I'll go to the store,
otherwise I'll send the house elf."

-s
 
A

AK

I also like this construct that works, I think, since 2.6:
code = dir[int(num):] if side == 'l' else dir[:-1*int(num)]
I wonder when this construct will finally start to look good.
It looks good to me. It follows a common English idiom:
"What are you doing tonight?"
"I'll be going to the movies, if I finish work early, otherwise I'll stay
home and watch a DVD."

I hate that idiom in English, too. If you're going to give me a forking
conditional, I want to know about it early.

Basically, I can handle
do x if y
pretty well, but
do x if y else z
always breaks my parser.

So in English, I might say "I'll go to the store if I have time", but
I'd rarely use "I'll go to the store if I have time, otherwise I'll send
the house elf"; instead, I'd say "If I have time, I'll go to the store,
otherwise I'll send the house elf."

-s

I actually find the shorter version slightly more readable than full
version. I think in English you'd say it in one sentence and that to me
feels like it should vaguely correspond to one line in code (perhaps
split over more than one line but that'd be due to long var names or
complex operations, not inherently).

The longer version may be like saying "I'll go to the store. If I have
time. If I don't have time. I will send the house elf."

It's a bit more readable to me because I can tell at a glance that a
single variable gets assigned a value based on a condition. With a
longer version it looks like something more complicated it going on, and
the eye has to look at all four lines and jump to another ident level.

By the way, it also looks far more readable in an editor where if and
else would be highlighted vs. all in plain colour.

-ak
 
S

Seebs

I actually find the shorter version slightly more readable than full
version. I think in English you'd say it in one sentence and that to me
feels like it should vaguely correspond to one line in code (perhaps
split over more than one line but that'd be due to long var names or
complex operations, not inherently).

I dunno, it always breaks my parser. The condition ends up between
the two dependents, and that doesn't work for me. I can have conditions
which are leading or trailing, but not infix.
It's a bit more readable to me because I can tell at a glance that a
single variable gets assigned a value based on a condition. With a
longer version it looks like something more complicated it going on, and
the eye has to look at all four lines and jump to another ident level.

Ahh! I see. There's several variants that could be discussed.

if condition:
x = y
else:
x = z

x = y if condition else z

And then the one I'm used to from other languages:

x = if condition then y else z

The other thing, from my point of view, is an ambiguity with a common
idiom I'm used to, again from other languages:

x = y if condition

If !condition, then nothing happens to x. So far as I can tell, that's
a syntax error in Python -- I can't use postfix if to modify a sentence,
because it's an expression thing.
By the way, it also looks far more readable in an editor where if and
else would be highlighted vs. all in plain colour.

I use syntax coloring in programming languages precisely as often, and
for precisely the same reasons, that I use it when writing in English.
Which is to say, if such a feature exists, I turn it off immediately
because it consistently distracts me from following the actual meaning
of code. Syntax is the least part of the meaning of code; giving extra
weight to syntax is pretty disruptive, IMHO.

-s
 
A

AK

I dunno, it always breaks my parser. The condition ends up between
the two dependents, and that doesn't work for me. I can have conditions
which are leading or trailing, but not infix.


Ahh! I see. There's several variants that could be discussed.

if condition:
x = y
else:
x = z

x = y if condition else z

And then the one I'm used to from other languages:

x = if condition then y else z

The other thing, from my point of view, is an ambiguity with a common
idiom I'm used to, again from other languages:

x = y if condition

If !condition, then nothing happens to x. So far as I can tell, that's
a syntax error in Python -- I can't use postfix if to modify a sentence,
because it's an expression thing.


I use syntax coloring in programming languages precisely as often, and
for precisely the same reasons, that I use it when writing in English.
Which is to say, if such a feature exists, I turn it off immediately
because it consistently distracts me from following the actual meaning
of code. Syntax is the least part of the meaning of code; giving extra
weight to syntax is pretty disruptive, IMHO.

Funny that you should say that, because I thought quite a few times that
it would be really awesome if some texts in English had syntax
highlighting. Obviously, not Brothers Karamazov, but something like a
tutorial, or a manual, or an online article. If key words were
highlighted, I'd be able to quickly glance over parts that are not
useful to me at the time, and find the interesting bits.

For instance, in the above paragraph I'd highlight 'awesome', 'English',
'syntax highlighting', 'tutorial', 'manual', 'online article',
'quickly glance over', 'not useful', 'find', 'interesting bits'.

It'd be like speed reading, except real!

-ak
 
S

Seebs

Funny that you should say that, because I thought quite a few times that
it would be really awesome if some texts in English had syntax
highlighting. Obviously, not Brothers Karamazov, but something like a
tutorial, or a manual, or an online article. If key words were
highlighted, I'd be able to quickly glance over parts that are not
useful to me at the time, and find the interesting bits.

That wouldn't be *syntax* highlighting, that'd be *semantic* highlighting.

Which people often do -- notice that I did it twice in that paragraph. But
that's the point -- you need to know what it *means* to make sensible
decisions about what to highlight. Syntax highlighting is precisely the
opposite, highlighting things for reasons that have nothing to do with
their semantic content. It distracts from the actual meaning of the
code.

In short, syntax highlighting would be like writing:

FUNNY *that* _you_ *should* /say/ *that*.
It'd be like speed reading, except real!

I don't understand this. So far as I know, the phrase "speed reading"
refers to various methods of reading much faster than most people read,
and is real but not exceptionally interesting.

-s
 
D

Dennis Lee Bieber

Funny that you should say that, because I thought quite a few times that
it would be really awesome if some texts in English had syntax
highlighting. Obviously, not Brothers Karamazov, but something like a
tutorial, or a manual, or an online article. If key words were
highlighted, I'd be able to quickly glance over parts that are not
useful to me at the time, and find the interesting bits.

For instance, in the above paragraph I'd highlight 'awesome', 'English',
'syntax highlighting', 'tutorial', 'manual', 'online article',
'quickly glance over', 'not useful', 'find', 'interesting bits'.

Syntax highlighting is more likely to identify: be, if, had, but,
like, or, were, are, not, and. That is, the (relatively) fixed
connectors between arbitrary nouns and concepts.

<something> be <something> if <something> had <something>. <something>
not <something>, but <something> like <something>, or <something>. If
<something> were <something> are not <something>, and <something>
 
A

AK

That wouldn't be *syntax* highlighting, that'd be *semantic* highlighting.

In case of programming, the effect is similar. I find that it allows me
to look quickly through code, scanning for something specific, e.g. the
next function, the next if/else block. If I'm looking for a print
statement, for example, I can quickly scan a whole screenful, looking
for a first highlighted long word (all the other highlighted keywords
will usually be if, else, and for). On the other hand, if I know I'm
looking for a variable, my eyes will filter out all the highlighted text
- strings and keywords. English is of course much less formal so you
have to understand the text to do useful highlighting. Anyway, I find it
very odd that anyone would not find it extremely useful (in code)!
Which people often do -- notice that I did it twice in that paragraph. But
that's the point -- you need to know what it *means* to make sensible
decisions about what to highlight. Syntax highlighting is precisely the
opposite, highlighting things for reasons that have nothing to do with
their semantic content. It distracts from the actual meaning of the
code.

I'm not always looking for meaning *immediately*. If I know there's a
single print statement in a function, I don't need to understand its
meaning to know that's the one print statement I need. (Or, if there's
two, I might know that I need the first one or at least I'll have 2
lines to look at instead of 75).
In short, syntax highlighting would be like writing:

FUNNY *that* _you_ *should* /say/ *that*.


I don't understand this. So far as I know, the phrase "speed reading"
refers to various methods of reading much faster than most people read,
and is real but not exceptionally interesting.

Afaik the idea is that you can read a novel at the speed of half a page
a second or so and understand it to the same extent as people who'd read
at a normal rate. Woody Allen joke: "I learned speed reading and
read War&Peace"; - it involves Russia.

-ak
 
A

AK

Syntax highlighting is more likely to identify: be, if, had, but,
like, or, were, are, not, and. That is, the (relatively) fixed
connectors between arbitrary nouns and concepts.

<something> be<something> if<something> had<something>.<something>
not<something>, but<something> like<something>, or<something>. If
<something> were<something> are not<something>, and<something>

Yes, I didn't mean that it's exactly the same, of course. Python being
much more formal than English means automatic syntax highlight can be
useful, as obviously many people find it; although this gave me an
interesting idea: if you had a long text that you wished to read
quickly, it might be more efficient to do syntax highlight of all verbs,
quickly scan through the text, then syntax highlight of all nouns, do
another quick scan, and then turn off syntax highlight and concentrate
on the parts that you did not understand while scanning. Is there a
program that'd do something like that?

-ak
 
C

Carl Banks

I also like this construct that works, I think, since 2.6:
code = dir[int(num):] if side == 'l' else dir[:-1*int(num)]

I wonder when this construct will finally start to look good.

I don't know if it'll ever look good, per se, but it looks better when
it's used in rule-exception sort of case:

something = rule if condition else exception

Then the "tacked-on" feel the "if condition else exception" part works
because it is actually tacked on.

Apart from occasions like this and throwaway one-liners I use regular
if-then statements. If Python had added the C-like a ? b : c, then
I'd use it a lot more, since that version is not inherently
unbalanced.


Carl Banks
 
S

Seebs

In case of programming, the effect is similar.

I have not found that to be the case. It's been exactly the same as syntax
highlighting in English would be -- it's wasting bandwidth telling me things
I already know, which slows down my perception of the things I'm trying
to find out.

Hmm. Actually, one thing -- I think I sometimes find it useful for a
couple of days on a new language I don't know yet. It's helpful then,
but once I've got my parser trained, it's a distraction.
Anyway, I find it
very odd that anyone would not find it extremely useful (in code)!

Yes, and I find it inexplicable that people find it useful.

News flash: Not all people think the same way. Film at 11. :)

I've tried to use syntax coloring editors, and I've always found that
they end up making me slower and less accurate at reading things,
because what they're highlighting isn't waht what I need to know.
Afaik the idea is that you can read a novel at the speed of half a page
a second or so and understand it to the same extent as people who'd read
at a normal rate. Woody Allen joke: "I learned speed reading and
read War&Peace"; - it involves Russia.

I dunno about that speed, but as I recall, my default reading speed for
English is about the range that people advertise in "speed reading"
courses, and I end up understanding text about as well as other
people do.

-s
 
A

AK

News flash: Not all people think the same way. Film at 11. :)
I've tried to use syntax coloring editors, and I've always found that
they end up making me slower and less accurate at reading things,
because what they're highlighting isn't waht what I need to know.

The way I see it, it's not meant to tell you something, it's
punctuation, it's as if you'd argue against periods and spaces at the
end of sentencesBecause the next sentence is capitalized anyway, so you
already know the last sentence ended. In the same way, in many cases
other punctuation is not absolutely necessary for understanding.

The other thing is of course that it helps you not to name your
variables using keywords and spot misspelled keywords.

-ak
 
S

Steven D'Aprano

Apart from occasions like this and throwaway one-liners I use regular
if-then statements. If Python had added the C-like a ? b : c, then I'd
use it a lot more, since that version is not inherently unbalanced.

Define "unbalanced".

Putting aside the over-use of punctuation, The C syntax feels unbalanced
to me. You have:

condition IF true-clause ELSE false-clause

so both clauses follow the test, that is, they're on the same side: ?--

This looks unbalanced to me. And it reads like something Yoda would say,
or Forth code.

But the Python syntax looks balanced to me:

true-clause IF condition ELSE false-clause

which is not only plain English, but perfectly balanced, with a clause on
either side of the test: -?-

Python's ternary-if puts the emphasis on the true-clause, while C's
ternary-if puts the emphasis on the test. I'm not convinced that this is
necessarily a better choice than Python's. It's a *valid* choice, but
better? I don't think so, but I accept that at least partially boils down
to subjective factors.
 
S

Steven D'Aprano

Afaik the idea is that you can read a novel at the speed of half a page
a second or so and understand it to the same extent as people who'd read
at a normal rate. Woody Allen joke: "I learned speed reading and read
War&Peace"; - it involves Russia.

My wife can read scarily fast. It's very something to watch her reading
pages as fast as she can turn them, and a few years ago she read the
entire Harry Potter series (to date) in one afternoon, and could gives a
blow-by-blow account of the plots, including a detailed critique of the
writing style and characters. But then, she feels that reading the Potter
series is a chore to be completed as fast as possible, rather than a
pleasure to be savored. She'll sometimes drag a new Terry Pratchett or
Stephen King novel out for as much as two days.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top