Which is the preferred way to concatenate a string in Python?

前端 未结 12 1010
眼角桃花
眼角桃花 2020-11-22 06:45

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         


        
12条回答
  •  庸人自扰
    2020-11-22 06:59

    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.

    • Python 3's f-Strings: An Improved String Formatting Syntax (Guide) (Speed test also included)
    • Formatted string literals
    • String Concatenation and Formatting
    • Splitting, Concatenating, and Joining Strings in Python

提交回复
热议问题