在Python中,可以使用split()方法按整个单词拆分字符串。默认情况下,split()方法按空格拆分字符串,但也可以指定其他分隔符。
以下是一个示例代码:
sentence = "This is a sample sentence."
# 按空格拆分字符串
words = sentence.split()
print(words)
# 输出: ['This', 'is', 'a', 'sample', 'sentence.']
# 按逗号拆分字符串
sentence2 = "apple, banana, orange"
fruits = sentence2.split(", ")
print(fruits)
# 输出: ['apple', 'banana', 'orange']
# 按整个单词拆分字符串
sentence3 = "I am happy"
word_list = sentence3.split(" ")
print(word_list)
# 输出: ['I', 'am', 'happy']
请注意,split()方法返回一个列表,其中包含拆分后的单词或子字符串。
上一篇:按整点进行SQL时间划定
下一篇:按整个行/列进行NumPy排序