有多种。以下是几种常见的方法:
sentence = "Hello, world! This is a sentence."
words = sentence.split()
print(words)
输出:
['Hello,', 'world!', 'This', 'is', 'a', 'sentence.']
推荐的腾讯云相关产品:腾讯云函数(Serverless 云函数服务),产品介绍链接地址:https://cloud.tencent.com/product/scf
import re
sentence = "Hello, world! This is a sentence."
words = re.findall(r'\b\w+\b', sentence)
print(words)
输出:
['Hello', 'world', 'This', 'is', 'a', 'sentence']
推荐的腾讯云相关产品:腾讯云API网关,产品介绍链接地址:https://cloud.tencent.com/product/apigateway
sentence = "Hello, world! This is a sentence."
words = []
current_word = ""
for char in sentence:
if char.isalnum():
current_word += char
elif current_word:
words.append(current_word)
current_word = ""
if current_word:
words.append(current_word)
print(words)
输出:
['Hello', 'world', 'This', 'is', 'a', 'sentence']
推荐的腾讯云相关产品:腾讯云容器服务(TKE),产品介绍链接地址:https://cloud.tencent.com/product/tke
这些方法可以根据具体的需求选择使用,根据字符串的格式和要求来返回单个单词。
领取专属 10元无门槛券
手把手带您无忧上云