python - 标点符号导致错误
问题描述
您好,我有一小段代码,当使用测试短语运行时,当代码遇到标点符号时会出错。我认为 word 的值为 null,但我尝试将其转换为字符串以防止出现错误 IndexError。我已经逐步完成了该程序,并获得了 '' 而不是 ' ' 的值,并且想知道其中的区别,以便我可以解决此问题。该代码适用于所有字母。
word = ''
quote = input('enter a 1 sentence quote, non-alpha words: ').lower()
for character in quote:
if character.isalpha() == True:
word += character
else:
if str(word[0]) >= 'h':
print(word.upper())
word = ''
else:
word = ''
示例输入:无论你走到哪里,全心全意地去期望输出:所有大写的单词都在自己的行中。随心所欲
解决方案
''
是一个完全有效的字符串。您不需要“投射”它或任何类似的东西。
但它是一个空字符串。所以它没有第一个字符word[0]
。如果您阅读错误消息:
IndexError: string index out of range
......这就是它告诉你的。问题不在于您没有字符串,而在于您的字符串不够大,无法包含第一个字符。
您在这里要做的是在询问其第一个字符之前检查空字符串:
if word and word[0] >= 'h':
print(word.upper())
word = ''
else:
word = ''
…或处理IndexError
:
try:
if word[0] >= 'h':
print(word.upper())
word = ''
else:
word = ''
except IndexError:
word = ''
通常,在 Python 中,只try
做某事并处理错误(更容易询问宽恕比权限,而不是Look Before You Leap)更惯用,但在某些情况下,首先检查会更具可读性,我认为这是其中一种情况。
推荐阅读
- react-native - 水平平面列表重新渲染更改 ListHeaderComponent
- android - 如何调试第三方flutter插件
- pytorch - PyTorch 中如何实现 Conv2d 的算法
- mysql - 通过迁移向导将 QODBC 连接到 MySQL 时出错
- android - 安排稍后执行的任务(时间+日期)android
- html - 如何使用简单的 HTML 表单将指标发布到 InfluxDB?
- c++ - OpenGL 纹理被镜像
- html - 概述 DIV 和图像
- google-apps-script - 从重复的电子表格运行 Google 脚本
- python - 我们可以对 K-Means 集群进行排名或为某些集群分配权重吗?