在 Python 中用逗号分割字符串
使用 str.split()
方法用逗号分割字符串,例如 my_list = my_str.split(',')
。 str.split
方法将在每次出现逗号时拆分字符串,并返回包含结果的列表。
# ✅ 在每次出现逗号时拆分字符串
my_str = 'one,two,three,four'
my_list = my_str.split(',')
print(my_list) # 👉️ ['one', 'two', 'three', 'four']
# ✅ 在每个空格或逗号上拆分字符串
my_str_2 = 'one two,three four five'
my_list_2 = my_str_2.replace(',', ' ').split(' ')
print(my_list_2) # 👉️ ['one', 'two', 'three', 'four', 'five']
str.split()
方法使用分隔符将字符串拆分为子字符串列表。
该方法采用以下 2 个参数:
- separator 在每次出现分隔符时将字符串拆分为子字符串
- maxsplit 最多完成最大拆分(可选)
如果在字符串中找不到分隔符,则返回仅包含 1 个元素的列表。
my_str = 'one'
my_list = my_str.split(',')
# 👇️ ['one']
print(my_list)
如果字符串中逗号分隔的单词之间有空格并且需要删除它,请使用 str.strip()
方法。
my_str = 'one , two , three ,four'
my_list = [item.strip() for item in my_str.split(',')]
print(my_list) # 👉️ ['one', 'two', 'three', 'four']
我们使用列表推导从每个字符串中删除前导和尾随空格。
列表推导用于对每个元素执行一些操作,或者选择满足条件的元素子集。
str.strip
方法返回删除了前导和尾随空格的字符串副本。
如果我们的字符串以逗号开头或结尾,将在列表中获得空字符串元素。
my_str = ',one,two,three,four,'
my_list = my_str.split(',')
print(my_list) # 👉️ ['', 'one', 'two', 'three', 'four', '']
我们可以使用 filter()
函数从列表中删除任何空字符串。
my_str = ',one,two,three,four,'
my_list = list(filter(None, my_str.split(',')))
print(my_list) # 👉️ ['one', 'two', 'three', 'four']
过滤器函数将一个函数和一个迭代器作为参数,并从迭代器的元素构造一个迭代器,函数为其返回一个真值。
如果为函数参数传递 None ,则可迭代的所有值为假的元素都将被删除。
所有不真实的值都被认为是假的。 Python 中的假值是:
- 定义为虚假的常量:None 和 False。
- 任何数字类型的 0(零)
- 空序列和集合:""(空字符串)、()(空元组)、[](空列表)、{}(空字典)、set()(空集)、range(0)(空范围)。
注意 filter()
函数返回一个过滤器对象,所以我们必须使用 list()
类将过滤器对象转换为列表。
如果我们需要在出现逗号和另一个字符时拆分字符串,请将逗号替换为另一个字符并在该字符上拆分。
my_str = 'one,two,three,four'
my_str_2 = 'one two,three four five'
my_list_2 = my_str_2.replace(',', ' ').split(' ')
print(my_list_2) # 👉️ ['one', 'two', 'three', 'four', 'five']
我们用空格替换所有出现的逗号,并在每个空格上拆分字符串。
我们可以通过用逗号替换每个出现的空格并在每个逗号上拆分来获得相同的结果。
my_str = 'one,two,three,four'
my_str_2 = 'one two,three four five'
my_list_2 = my_str_2.replace(' ', ',').split(',')
print(my_list_2) # 👉️ ['one', 'two', 'three', 'four', 'five']
相关阅读:
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。