patternpythonMinor
Print a space separated list in Python
Viewed 0 times
spaceseparatedprintpythonlist
Problem
I am trying to solve the common "print a character after every item in a list, except the last one" problem.
I do not want to use list indexes. There are a couple of simple ways to do this in Python, but I am not sure how to apply them to my code.
Is there a more readable/couple liner way to do this?
Note: Code works in both Python 2 and Python 3.
I do not want to use list indexes. There are a couple of simple ways to do this in Python, but I am not sure how to apply them to my code.
Is there a more readable/couple liner way to do this?
def echo(*args):
for data in args:
if data is args[-1]:
ender = ''
else:
ender = ' '
if isinstance(data, six.string_types) \
or isinstance(data, six.integer_types):
print_(data, end=ender)
else:
op = getattr(data, '__str__', None)
if op:
print_(data.__str__(), end=ender)
else:
LOG.error("echo called with an unsupported data type")
print_('')Note: Code works in both Python 2 and Python 3.
Solution
I might be misreading your code, but it looks like all you want is:
For something a bit more manual:
In terms of reviewing your actual code, on top of the issues Morwenn raises, note that:
simplifies to:
However, it is rare to call magic methods directly in Python; normally you'd just do
I would include the filtering as a separate function:
Then
def echo(*args):
six.print_(*args, sep=" ", end="")For something a bit more manual:
def echo(*args):
six.print_(" ".join(map(str, args)), end="")In terms of reviewing your actual code, on top of the issues Morwenn raises, note that:
op = getattr(data, '__str__', None)
if op:simplifies to:
if hasattr(data, '__str__'):However, it is rare to call magic methods directly in Python; normally you'd just do
str(data) and let Python call __str__. This is safer, as although an old-style class may not implement __str__, you can still get e.g. '' via str(...). I would include the filtering as a separate function:
def valid(arg):
"""Include a docstring to explain your filtering rules."""
if (isinstance(data, (six.string_types, six.integer_types)) or
hasattr(data, '__str__')):
return True
LOG.error("echo called with an unsupported data type")
return FalseThen
echo can use filter:def echo(*args):
six.print_(*filter(valid, args), sep=" ", end="")Code Snippets
def echo(*args):
six.print_(*args, sep=" ", end="")def echo(*args):
six.print_(" ".join(map(str, args)), end="")op = getattr(data, '__str__', None)
if op:if hasattr(data, '__str__'):def valid(arg):
"""Include a docstring to explain your filtering rules."""
if (isinstance(data, (six.string_types, six.integer_types)) or
hasattr(data, '__str__')):
return True
LOG.error("echo called with an unsupported data type")
return FalseContext
StackExchange Code Review Q#60421, answer score: 8
Revisions (0)
No revisions yet.