杰瑞科技汇

python str to list

Of course! Converting a Python string to a list is a very common task. The best method to use depends on how you want to split the string.

Here are the most common ways, from simplest to more advanced.

Split a String by a Delimiter (Most Common)

This is the most frequent use case. You have a string where items are separated by a specific character (like a comma, space, or tab).

Method: str.split()

The split() method is your go-to tool. By default, it splits on any whitespace and removes extra spaces.

Example 1: Split by Whitespace (Default Behavior)

sentence = "hello world python"
word_list = sentence.split()
print(word_list)
# Output: ['hello', 'world', 'python']

Example 2: Split by a Specific Character (Comma)

data = "apple,banana,cherry,orange"
fruit_list = data.split(',')
print(fruit_list)
# Output: ['apple', 'banana', 'cherry', 'orange']

Example 3: Splitting a File Path

path = "/home/user/documents/report.txt"
path_parts = path.split('/')
print(path_parts)
# Output: ['', 'home', 'user', 'documents', 'report.txt']

Key Parameters for split():

  • sep (separator): The character or string to use as the delimiter.
    • If sep is not provided or is None, it splits on any whitespace, and consecutive whitespace is treated as a single separator.
  • maxsplit: The maximum number of splits to perform. The list will have maxsplit + 1 elements.
# Using maxsplit
data = "one,two,three,four,five"
# Only split on the first comma
first_split = data.split(',', 1)
print(first_split)
# Output: ['one', 'two,three,four,five']

Get a List of Individual Characters

If you want every single character in the string to be an element in the list.

Method 1: list() Constructor (Most Pythonic)

This is the cleanest and most direct way.

my_string = "python"
char_list = list(my_string)
print(char_list)
# Output: ['p', 'y', 't', 'h', 'o', 'n']

Method 2: List Comprehension (More Flexible)

This is useful if you want to process each character as you create the list.

my_string = "PyThOn"
# Convert to lowercase and create a list of characters
char_list_lower = [char for char in my_string]
print(char_list_lower)
# Output: ['P', 'y', 'T', 'h', 'O', 'n']
# A more complex example: get only the vowels
vowels = "aeiouAEIOU"
vowel_list = [char for char in my_string if char in vowels]
print(vowel_list)
# Output: ['y', 'T', 'O']

Get a List of Lines from a Multi-line String

If your string contains newline characters (\n), you can easily split it into a list of lines.

Method: str.splitlines()

This method is specifically designed to handle different types of line boundaries (\n, \r\n, \r, etc.) correctly.

multiline_string = "First line\nSecond line\nThird line"
line_list = multiline_string.splitlines()
print(line_list)
# Output: ['First line', 'Second line', 'Third line']

Note: You could also use split('\n'), but splitlines() is generally more robust as it handles all line-ending conventions.


Summary: Which Method to Use?

Your Goal Method Example
Split a string by a separator (e.g., space, comma) str.split() "a,b,c".split(',')['a', 'b', 'c']
Get a list of all characters list() list("abc")['a', 'b', 'c']
Get a list of lines from a string str.splitlines() "line1\nline2".splitlines()['line1', 'line2']
Create a list from a string with custom logic List Comprehension [c.upper() for c in "abc"]['A', 'B', 'C']
分享:
扫描分享到社交APP
上一篇
下一篇