是否可以将句子拆分为字符串列表并大写同一行中的字符串列表?

问题描述

例如:

我想输入这个 edit('Let's do this!') 并得到这个 ['LET'S','DO','THIS!'] 答案。

这是我目前的代码

### START FUNCTION
def edit(sentence):
    result = (sentence.split())
    return result
### END FUNCTION

edit('Hello,how are you?')

关于在中间代码行“result = ...”中添加什么的任何解决方

解决方法

当然,您可以使用列表理解将句子中的每个单词转换为大写。

def edit(sentence):
    return [word.upper() for word in sentence.split()]

如果你想让编辑功能更长一点..那么可以

def edit(sentence):
    result = (sentence.split())
    result = [word.upper() for word in result]
    return result

另一种方法是使用 map 函数将上层函数应用于列表中的每个项目。

result = list(map(str.upper,sentence.split()))

如果您想忽略标点符号,例如,正则表达式可以帮助您拆分单词并忽略非单词字符

result = [word.group(0).upper() for word in re.finditer("([\w]+)(\W|$)",sentence)]