简体   繁体   English

为什么我得到“IndexError:字符串索引超出范围”?

[英]Why do I get "IndexError: string index out of range"?

I'm currently a beginner to python and coding in general.我目前是 Python 和编码的初学者。

I am doing this quiz online which tasks you to remove signs (*_`~) from the front and end of a string.我在网上做这个测验,任务是从字符串的前端和末尾删除符号 (*_`~)。 Eg.(~~hidden ~ tilde~~ will be changed to hidden ~ tilde) keeping the sign in the middle.例如。(~~hidden ~ tilde~~ 将变为hidden ~ tilde) 将符号保持在中间。

This is my code:这是我的代码:

string = input()
signs = " *_`~ "
for sign in string:
    if sign in signs:
        if sign == string[0]:
            string = string.lstrip(sign)
            string = string.rstrip(sign)
print(string)

Which gets this error: IndexError: string index out of range得到这个错误:IndexError: string index out of range

I'm just a noob trying to get started on python..plz help :(我只是一个尝试开始使用 python..plz help :(

The entire code is unneccessary.整个代码是不必要的。 Just use strip只需使用条带

signs = " *_`~ "
string = "*fo * o*"
print(string.strip(signs)) # fo * o

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM