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)
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)
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
out_list = []
format
a header and append it to out_listin_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?
Hello $name
and Bonjour $name