0

Considering the example below, why would anyone choose the first print instead of the second?

def main():
    name = input("Input your name:")
    age = int(input("Input you age:"))

    print("Your name is " + name + " and you are " + str(age) + " years old.")
    print("Your name is", name, "and you are" , age, "years old.")

if __name__ == "__main__":
    main()

It seems to me that print("text", var, "text") is more straightforward, since there's no need to explicitly convert our int to str.

Are there any relevant use cases for the print("text"+str(var)+"text") format?

rodrigocfaria
  • 440
  • 4
  • 11
  • 1
    `+` generically concatenates strings. Of course you want to be able to concatenate strings. There are way better options to output numbers in strings, but turning the number into a string and concatenating it is an option which simply exists because type casting and concatenation exists. No, it's in no way better and should probably never be your go-to, but there it is. – deceze Dec 26 '21 at 20:22
  • I think that there are no advantages between the two methods, its just a matter of taste and the kind of print you are doing. – Jucelio Quentino Dec 26 '21 at 20:22
  • 1
    See https://stackoverflow.com/questions/10043636/any-reason-not-to-use-to-concatenate-two-strings – mkrieger1 Dec 26 '21 at 20:24

1 Answers1

3

The usual way of doing this is formatting like:

print(f"Your name is {name} and you are {age} years old.")

Considering the example below, why would anyone choose the first print instead of the second?

Well, the first way (concatenation of strings and expressions converted to strings) is obsolete and unusable for me, since we have proper formatting (like my example above). We can construct any string we want straightforwardly and clearly.

If we apply the same logic to *args approach, as for me, the outcome is the same.

Yevgeniy Kosmak
  • 3,561
  • 2
  • 10
  • 26