python - Python 中的索引错误:“字符串索引超出范围”
问题描述
我是一名初学者程序员,作为练习,我想编写一个代码,将句子中的每个单词打印到一个新行中,因为该单词以 hz 开头。
这是我制作的代码:
random_phrase = "Wheresoever you go, go with all your heart"
word = ""
for ltr in random_phrase:
if ltr.isalpha():
word += ltr
else:
if word.lower()[0] > "g":
print(word)
word = ""
else:
word = ""
在它打印你之后,有一行空白,然后发生索引错误。我做错了什么?
解决方案
试试这个打印以 hz 开头的句子的每个单词:
import string
# make the sentence lower case
random_phrase = "Wheresoever you go, go with all your heart".lower()
# split the sentence with space as separator into a list
words = random_phrase.split(" ")
start = "h"
end = "z"
# string.ascii_lowercase will give the lowercase letters ‘abcdefghijklmnopqrstuvwxyz’
letters = string.ascii_lowercase
# take the range h-z
allowed = letters[letters.index(start):letters.index(end)+1]
# iterate through each word and check if it starts with (h-z)
for word in words:
if any(word.startswith(x) for x in allowed):
print(word)
使用正则表达式:
import re
random_phrase = "Wheresoever you go, go with all your heart"
words = [s for s in random_phrase.split() if re.match('^[h-z,H-Z]', s)]
for word in words:
print(word)
推荐阅读
- jquery - Jquery 使用 Wordpress 的 Elementor 通过灯箱加载时自动播放 Vimeo 视频
- javascript - OnClick 添加一行来自数据库 laravel/js 的数据
- sql-server - 如何将表中的字段链接到另一个表中字段的总和?
- javascript - Copy paste from excel, difference between line break in cell and row delimiter
- reinforcement-learning - 深度 Q 学习 - Cartpole 环境
- snmp - 如何在 pysnmp 代理端的自定义 MIB 文件中设置值?
- oracle - Oracle:缓冲区命中率与缓冲区高速缓存命中率
- typescript - 为什么 TypeScript 会抛出有关 GQL 查询类型试图重新定义自身的错误?
- java - 处理:函数“toArray()”需要如下参数:“toArray(T[])”
- swiftui - SwiftUI:通过导入来分离视图