欢迎访问宙启技术站
智能推送

用PYTHON中的SPLIT函数来分割字符串

发布时间:2023-07-06 04:50:41

split() 函数是 Python 中内置的字符串方法,用于将字符串分割为子字符串,并返回一个包含分割后的子字符串的列表。

split() 函数的语法如下:

str.split(sep=None, maxsplit=-1)

其中,

- sep:指定分割的字符串,如果不指定,默认使用空格作为分隔符,可以是一个字符或者多个字符的组合。

- maxsplit:指定分割的次数,如果不指定,默认为 -1,即分割所有匹配的子字符串。

下面是一个示例,演示如何使用 split() 函数分割字符串:

# 使用空格进行分割
text = "This is a sample sentence."
words = text.split()
print(words)  # 输出:['This', 'is', 'a', 'sample', 'sentence.']

# 使用逗号进行分割
text = "apple,banana,orange"
fruits = text.split(",")
print(fruits)  # 输出:['apple', 'banana', 'orange']

# 指定分割次数
text = "python-programming-tutorial"
parts = text.split("-", 1)
print(parts)  # 输出:['python', 'programming-tutorial']

希望以上示例能帮到你!