Is it better to `join` or `format` strings?

Viewed 728

Which is faster - more efficient - more proper?

join

string = "Hello"

concatenate = " ".join([string, "World"])

print(concatenate)

or

format

string = "Hello"

concatenate = f"{string} World"

print(concatenate)
2 Answers

We can use join() function to concatenate string with a separator. It’s useful when we have a sequence of strings, for example list or tuple of strings. Let's say -

s1 = 'Hello'
s2 = 'World'

print('Concatenated String using join() =', "".join([s1, s2]))
Output:
Concatenated String using join() = HelloWorld

print('Concatenated String using join() and whitespaces =', " ".join([s1, s2]))
Output:
Concatenated String using join() and spaces = Hello World

.format function - We can use string format() function for string concatenation and formatting too

s1 = 'Hello'
s2 = 'World'

s3 = f'{s1} {s2}'
print('String Concatenation using f-string =', s3)
String Concatenation using f-string = Hello World

name = 'Pankaj'
age = 34
d = Data(10)

print(f'{name} age is {age} and d={d}')
Pankaj age is 34 and d=Data[10]

They can do different things and be used together.

In your simple example, format (or sprintf or Template versions) is simpler to read and more Pythonic.

But consider a document generator with a header line and content lines for each item in a in_list.

You

  • create an empty out_list = []
  • format a header and append it to out_list
  • loop through each item in in_list, format and append to out_list
  • ”\n”.join(out_list) to get your whole document

(At this point Jinja2 might also be useful)

Why use Template ($name) or sprintf (%(name)s) rather than f-string?

  • Python version
  • multiple possible templates i.e. Hello $name and Bonjour $name
  • Templates are defined elsewhere, possibly in another function or in a file.
  • For extra rabbit holes, the templates themselves could be generated by code. Let’s say a system to dynamically display fields resulting from arbitrary sql queries.
Related