python如何根据逗号拆分字符串
时间: 2024-05-03 22:16:23 浏览: 8
可以使用`split()`方法来根据逗号拆分字符串。示例代码如下:
```python
string = "apple,banana,orange"
result = string.split(",")
print(result)
```
执行结果为:
```
['apple', 'banana', 'orange']
```
其中`,`作为参数传递给`split()`方法,表示以逗号为分隔符拆分字符串。返回的结果是一个列表,列表中的每个元素就是原字符串中以逗号分隔的各个部分。
相关问题
python以逗号拆分字符串
好的,这是一个关于Python的技术问题,可以回答。如果你想要将一个字符串按照逗号拆分成多个子字符串,可以使用split()方法,例如:
str = "apple, banana, cherry"
split_str = str.split(", ")
print(split_str)
这样就可以将字符串按照逗号和空格拆分成一个列表。
python 拆分字符串
在 Python 中,你可以使用 `split()` 方法来拆分字符串。
语法如下:
```python
string.split(separator, maxsplit)
```
其中 `separator` 参数是用来指定分隔符的,默认情况下是空格;`maxsplit` 参数是用来指定拆分的次数,可选参数,默认值为 -1,表示不限制次数。
示例代码:
```python
string = "Hello, World!"
# 拆分字符串,默认按空格分隔
words = string.split()
# 拆分字符串,按逗号分隔
words = string.split(',')
# 拆分字符串,只分隔一次
words = string.split(',', 1)
```
以上代码中,`words` 即为拆分后得到的字符串列表。