How to concatenate items in a list to a single string?

后端 未结 11 2013
北荒
北荒 2020-11-21 05:59

Is there a simpler way to concatenate string items in a list into a single string? Can I use the str.join() function?

E.g. this is the input [\'t

11条回答
  •  野性不改
    2020-11-21 06:07

    Without .join() method you can use this method:

    my_list=["this","is","a","sentence"]
    
    concenated_string=""
    for string in range(len(my_list)):
        if string == len(my_list)-1:
            concenated_string+=my_list[string]
        else:
            concenated_string+=f'{my_list[string]}-'
    print([concenated_string])
        >>> ['this-is-a-sentence']
    

    So, range based for loop in this example , when the python reach the last word of your list, it should'nt add "-" to your concenated_string. If its not last word of your string always append "-" string to your concenated_string variable.

提交回复
热议问题