Python 获取列表中的第二个字符

Python 获取列表中的第二个字符,python,Python,我试图创建一个循环函数,如果句子中每个单词的第二个字符='R',那么它将被打印出来 st = 'Print only the words' for word in st.split(): if word[1] == 'r': print(word) 我不断得到错误字符串索引超出范围 您可以使用len(word)

我试图创建一个循环函数,如果句子中每个单词的第二个字符='R',那么它将被打印出来

st = 'Print only the words'

for word in st.split():
    if word[1] == 'r':
        print(word)

我不断得到错误字符串索引超出范围

您可以使用
len(word)<2
显式筛选出单词,这将解决
索引器的问题:

st = 'Print only a word with at least two letters that has r in index 2'

for word in st.split():
    if len(word) > 1 and word[1] == 'r':
        print(word)
# 'Print'

如果单词只有一个字母,则索引超出范围

st = 'Print only a word, orange'

for word in st.split():
    if len(word) > 1:
        if word[1] == 'r':
            print(word)

使用regexp怎么样

import re
re.findall(r'\b(.r.*?)\b',"Print the string or trim the string your lucky dry day")
[‘打印’、‘修剪’、‘干燥’]


对我有用。你确定这就是确切的例子?没有像
'a'
这样的单字母单词的输入数据?它也适用于我。要么捕获异常,要么检查字符串长度。@schwobaseglg没有。这只是我试图实现的一个简化版本。我想我在qn的某个地方犯了个错误!谢谢在问题陈述中,您提到了
R
,在代码中您正在使用
R
。你的第二个字符区分大小写吗?我的答案和安德鲁·里斯的答案在操作上是相同的。他比我早四分钟回答了,因此应该得到表扬。我将保留我的答案,因为对于python的新用户来说,拆分if可能更容易阅读。