Since Python\'s string can\'t be changed, I was wondering how to concatenate a string more efficiently?
I can write like it:
s += string
You can do in different ways.
str1 = "Hello"
str2 = "World"
str_list = ['Hello', 'World']
str_dict = {'str1': 'Hello', 'str2': 'World'}
# Concatenating With the + Operator
print(str1 + ' ' + str2) # Hello World
# String Formatting with the % Operator
print("%s %s" % (str1, str2)) # Hello World
# String Formatting with the { } Operators with str.format()
print("{}{}".format(str1, str2)) # Hello World
print("{0}{1}".format(str1, str2)) # Hello World
print("{str1} {str2}".format(str1=str_dict['str1'], str2=str_dict['str2'])) # Hello World
print("{str1} {str2}".format(**str_dict)) # Hello World
# Going From a List to a String in Python With .join()
print(' '.join(str_list)) # Hello World
# Python f'strings --> 3.6 onwards
print(f"{str1} {str2}") # Hello World
I created this little summary through following articles.