Skip to main content
added 398 characters in body
Source Link
xnor
  • 146.6k
  • 26
  • 279
  • 652

Use extended slicing to select one string from many

>>> for x in 0,1,2:print"fbboaaorz"[x::3]
... 
foo
bar
baz
>>> for x in 0,1,2:print"fbboaaorz"[x::3]
... 
foo
bar
baz

vs

>>> for x in 0,1,2:print["foo","bar","baz"][x]
... 
foo
bar
baz
>>> for x in 0,1,2:print["foo","bar","baz"][x]
... 
foo
bar
baz

In this Boolean two-string case, one can also write

b*"string"or"other_string"

for

["other_string","string"][b]

Unlike interleaving, this works for strings of any length, but can have operator precedence issues if b is instead an expression.

Use extended slicing to select one string from many

>>> for x in 0,1,2:print"fbboaaorz"[x::3]
... 
foo
bar
baz

vs

>>> for x in 0,1,2:print["foo","bar","baz"][x]
... 
foo
bar
baz

Use extended slicing to select one string from many

>>> for x in 0,1,2:print"fbboaaorz"[x::3]
... 
foo
bar
baz

vs

>>> for x in 0,1,2:print["foo","bar","baz"][x]
... 
foo
bar
baz

In this Boolean two-string case, one can also write

b*"string"or"other_string"

for

["other_string","string"][b]

Unlike interleaving, this works for strings of any length, but can have operator precedence issues if b is instead an expression.

Source Link
gnibbler
  • 15.2k
  • 4
  • 49
  • 75

Use extended slicing to select one string from many

>>> for x in 0,1,2:print"fbboaaorz"[x::3]
... 
foo
bar
baz

vs

>>> for x in 0,1,2:print["foo","bar","baz"][x]
... 
foo
bar
baz