-1

Is there a way to make the print_str function be more concise and becomes one line?

   def print_str(str):
        if len(str)>0:
            print(str + ", "+ "hi")
        else:
            print("hi")

   if __name__ == '__main__':
        print_str(("John"))
        print_str((""))

In java we can do something like

print(str + (str.equals("") ? "" : ", ") + "hi");
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
william007
  • 17,375
  • 25
  • 118
  • 194

1 Answers1

0

Yes you can do something similar in a one line if else statement with python. In your example it would be like this:

print(str + ("" if str == "" else ", ") + "hi")

The format is X if condition else Y where X is the result if the condition is true and Y is the result otherwise.

Karl
  • 1,664
  • 2
  • 12
  • 19
  • Or `print(str + ",hi" if len(str) > 0 else "hi")` – OneCricketeer Sep 05 '18 at 03:18
  • 1
    @cricket_007: Or just test `str` instead of `len(str) > 0` or `not str` instead of `str == ""` following [the PEP8 recommendation](https://www.python.org/dev/peps/pep-0008/#programming-recommendations): "For sequences, (strings, lists, tuples), use the fact that empty sequences are false", which explicitly `if seq` and `if not seq` as preferable to any test involving `len`. – ShadowRanger Sep 05 '18 at 03:26