1
name = 'John'

#basic method
print('Hello, his name is ' + name)

#.format method
print('Hello, his name is {}'.format(name))

#f-string literal method
print(f'Hello, his name is {name}')

All are viable ways to concatenate and outputs the same thing, but why would I choose one over the other?

smci
  • 32,567
  • 20
  • 113
  • 146
DanONS
  • 195
  • 1
  • 2
  • 7
  • Which one do you find the most readable? – khelwood Aug 03 '18 at 08:17
  • Probably the first one, but are there additional functionalities by using the others? – DanONS Aug 03 '18 at 08:19
  • 1
    https://stackoverflow.com/questions/13451989/pythons-many-ways-of-string-formatting-are-the-older-ones-going-to-be-deprec and the linked questions within are highly relevant – Chris_Rands Aug 03 '18 at 08:28
  • 1
    Related and near-duplicate: [Pythons many ways of string formatting — are the older ones (going to be) deprecated?](https://stackoverflow.com/questions/13451989/pythons-many-ways-of-string-formatting-are-the-older-ones-going-to-be-deprec), and the older question [Python string formatting: % vs. .format](https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format) – smci Aug 03 '18 at 23:08

1 Answers1

2

#1 won't work if name isn't a string.

#2 is fine on any version but is a little unwieldy to type. Generally the best for compatibility across python versions.

#3 If the best option in terms of readability (and performance). But it only works on python3.6+, so not a good idea if you want your code to be backwards compatible.

There's also #4, old style formatting ala %s, %d, etc, which are now discouraged in favour for str.format.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • 1
    all but #1 also allow the use of [Format Specification Mini-Language](https://docs.python.org/3/library/string.html#formatspec) to tailor your output – Patrick Artner Aug 03 '18 at 08:24