3

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)
thehammerons
  • 55
  • 1
  • 5
  • 7
    It’s mostly opinion, but I prefer the second in this case. Join seems more appropriate when you have a list to begin with, but here you are making a new list just to call join. – Mark Jun 14 '20 at 00:29
  • 3
    https://stackoverflow.com/questions/40714555/python-string-formatting-is-more-efficient-than-format-function I would check this post out. It's might help you. – burntchowmein Jun 14 '20 at 00:35
  • @MarkMeyer I would personally use `format` as well, but a downside to it is that it is only available for python 3.6 and above. – 10 Rep Jun 14 '20 at 03:52
  • The F-string is far faster, but not appropriate when you don't know how many strings you'll be passing to `join`. – chepner Jun 14 '20 at 17:00

2 Answers2

0

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]
0

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.
JL Peyret
  • 10,917
  • 2
  • 54
  • 73