1. 使用 `split()` 方法:
s = "apple,banana,pear"
lst = s.split(',') 使用逗号作为分隔符
print(lst) 输出:['apple', 'banana', 'pear']
2. 使用 `splitlines()` 方法:
s = "book\npaper\nback"
lst = s.splitlines() 使用换行符作为分隔符
print(lst) 输出:['book', 'paper', 'back']
3. 使用正则表达式进行分割:
import re
s = "face, vehicle, head hat"
lst = re.split(r'[ ,]+', s) 使用逗号和空格作为分隔符
print(lst) 输出:['face', 'vehicle', 'head', 'hat']
4. 使用字符串切片进行切分:
s = "hello world"
words = s.split() 默认按空格分割
print(words) 输出:['hello', 'world']
5. 使用 `strip()` 方法去除字符串两端的空白字符:
s = " hello world "
s = s.strip() 去除开头和结尾的空格
print(s) 输出:"hello world"
以上是Python3中切分字符串的一些常见方法。您可以根据需要选择合适的方法进行操作