Home >Backend Development >Python Tutorial >How to Join a List of Strings into a Single String?

How to Join a List of Strings into a Single String?

Barbara Streisand
Barbara StreisandOriginal
2024-12-21 11:48:20847browse

How to Join a List of Strings into a Single String?

How to Concatenate Items in a List into a Single String

Question: How can I combine a list of individual strings into a single, continuous string? For instance, if I have the list ['this', 'is', 'a', 'sentence'], how can I obtain the string "this-is-a-sentence"?

Answer: To concatenate the strings in the list, use the str.join method.

For example:

words = ['this', 'is', 'a', 'sentence']

# Use '-' as the separator
separator = '-'
joined_string = separator.join(words)
print(joined_string)  # Output: this-is-a-sentence

# Alternatively, use ' ' as the separator
separator = ' '
joined_string = separator.join(words)
print(joined_string)  # Output: this is a sentence

The str.join method takes a string as its argument, which acts as the separator between the list items when combined into a single string. You can customize the separator to suit your needs, such as using a space for words or a dash for components.

The above is the detailed content of How to Join a List of Strings into a Single String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn