Question

I was trying to use a ternary to print out a string if something was true and something else if it wasn't (simple enough, right?). It gives no errors and doesn't seem like it would cause any trouble. However, when running...

print('[',dr+1,']\t',d[dr] if fullpath else '[',dr+1,']\t',d[dr].split("/")[len(d[dr].split("/"))-2], sep='')

...it prints out

'[',dr+1,']\t'

twice. For example, it prints this:

[1] [1] Accoustic
[2] [2] Classical
[3] [3] Epic
[4] [4] Rock
[5] [5] Spoof
[6] [6] Techno & Electronic

If you want, in order to see what the variables are (which shouldn't matter since this is just a concept issue), you can see the rest of the code here

Thinking that it might be the variables, I tried printing the statements separately (no ternary) and they came out as I expected (i.e. without the odd duplication). Knowing that the variables were fine, I tried enclosing the strings with parenthesis (in an attempt to keep the strings from mixing) but, since python interprets them literally, they came out as arrays instead of strings. Also, + symbols (in lieu of commas) don't work because python can't combine the data type. I ended up changing the statement to

print('[',dr+1,']\t',d[dr]) if fullpath else print('[',dr+1,']\t',d[dr].split("/")[len(d[dr].split("/"))-2], sep='')

and it works fine.

Not so great coding aside, why is that first string getting printed twice?

Was it helpful?

Solution

Allow me to break it down for you...

print(('['), (dr+1), (']\t'), (d[dr] if fullpath else '['), (dr+1), (']\t'), (d[dr].split("/")[len(d[dr].split("/"))-2]), sep='')

See the problem?

print(*(('[',dr+1,']\t', d[dr]) if fullpath else ('[',dr+1,']\t', d[dr].split("/")[len(d[dr].split("/"))-2])), sep='')

OTHER TIPS

I'm not sure why it wouldn't print twice:

print('[',dr+1,']\t',       #first one
      d[dr] if fullpath else '[',
      dr+1,']\t',           #second one (most of it anyway)
      d[dr].split("/")[len(d[dr].split("/"))-2],
      sep='')

Depending on fullpath, your statement could look like

print('[',dr+1,']\t',       #first one
      d[dr],dr+1,']\t',     #second one (more or less)
      d[dr].split("/")[len(d[dr].split("/"))-2], 
      sep='')

or it could look like:

print('[',dr+1,']\t',
      '[',dr+1,']\t',
      d[dr].split("/")[len(d[dr].split("/"))-2], 
      sep='')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top