python-3.7 - 如何在作为字符串一部分的单词中查找字母并将其删除?(用 if 语句列出推导式)
问题描述
我正在尝试从字符串中删除元音。具体来说,从超过 4 个字母的单词中删除元音。
这是我的思考过程:
(1) 首先,将字符串拆分成一个数组。
(2) 然后,遍历数组并识别超过 4 个字母的单词。
(3) 第三,用“”代替元音。
(4) 最后,将数组重新连接成一个字符串。
问题:我不认为代码在数组中循环。谁能找到解决方案?
def abbreviate_sentence(sent):
split_string = sent.split()
for word in split_string:
if len(word) > 4:
abbrev = word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
sentence = " ".join(abbrev)
return sentence
print(abbreviate_sentence("follow the yellow brick road")) # => "fllw the yllw brck road"
解决方案
我刚刚发现“abbrev = words.replace ...”行不完整。
我将其更改为:
abbrev = [words.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") if len(words) > 4 else words for words in split_string]
我在这里找到了解决方案的一部分:在列表中查找和替换字符串值。
它被称为列表理解。
我还发现了使用 If 语句的列表理解
新的代码行如下所示:
def abbreviate_sentence(sent):
split_string = sent.split()
for words in split_string:
abbrev = [words.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
if len(words) > 4 else words for words in split_string]
sentence = " ".join(abbrev)
return sentence
print(abbreviate_sentence("follow the yellow brick road")) # => "fllw the yllw brck road"
推荐阅读
- android - 无法从服务器改造android的响应中提取数组,结果我崩溃了?
- javascript - 如何为 highchart 上的 tickPosition 提供填充?
- ios - 将 Gamesparks 与 iOS 集成的问题
- docker - 无法使用 ADD 或 COPY 替换 docker 映像中的文件
- oauth-2.0 - Yii2 Auth Client for Google 在登录后给出错误重定向 URI 不匹配
- javascript - 如何直接从javascript中的文件上传按钮上传图像
- excel - 在 Audit Trail 中记录多个单元格的复制粘贴和删除
- php - 雄辩关系上的 toSql() 返回`where id = null`
- python - 在 python 上的地图上绘制数据
- sql-order-by - 在 SAP Hana 中使用排序规则的 ORDER_BY