Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我试图确定一个词是否存在,而不考虑大小写,但希望根据大小写给出单独的回答_Python_Case Sensitive - Fatal编程技术网

Python 我试图确定一个词是否存在,而不考虑大小写,但希望根据大小写给出单独的回答

Python 我试图确定一个词是否存在,而不考虑大小写,但希望根据大小写给出单独的回答,python,case-sensitive,Python,Case Sensitive,这是可行的,但我得到一个错误声明,说字符串索引超出范围?? 有什么想法吗?检查rs[2]=“b”要求行中的所有单词至少有3个字符长…由于字符串可能不够长,因此出现了错误。最有可能的情况是在使用索引的中等大小写检查中 你有一个选择,就是用这个方法来检查你的“中等大小写”。这提供了一种实现目标的方法: r = input("Line: ") r = r.split() for rs in r: if rs == "robot": print("There is a small robot

这是可行的,但我得到一个错误声明,说字符串索引超出范围??
有什么想法吗?

检查rs[2]=“b”要求行中的所有单词至少有3个字符长…

由于字符串可能不够长,因此出现了错误。最有可能的情况是在使用索引的中等大小写检查中

你有一个选择,就是用这个方法来检查你的“中等大小写”。这提供了一种实现目标的方法:

r = input("Line: ")
r = r.split()
for rs in r:
  if rs == "robot":
    print("There is a small robot in the line.")
  elif rs == "ROBOT":
    print("there is a big robot in the line.")
  elif rs[0] == "r" or "R" and rs[1] == "o" or "O" and rs[2] == "b" or "B" and rs[3] == "O" or"o" and rs[-1] == "T" or "t":
    print("There is a medium sized robot in the line.")
  else:
    print("There are no robots in the line.")
产出:

Line:机器人
小机器人
生产线:中型机器人
中型机器人
线条:一个大型机器人
大机器人
生产线:没有自动机器
没有机器人
关于这段代码,您会注意到的一点是,我正在保存结果,直到循环结束。否则,对于输入字符串中的每个单词,您将获得多行输出

例如:

Line:机器人很酷
没有机器人
小机器人
没有机器人
没有机器人

以前有人问过如何在Python中进行不区分大小写的字符串比较的问题

假设您确定了执行区分大小写比较(CS)和不区分大小写比较(CI)的正确方法,那么您可能希望按照以下方式重写算法(伪代码,而不是Python代码):

如果比较语句是固定的,您当前的算法将为任何情况下与“robot”不匹配的每个单词打印“行中没有机器人”,即使行中的一个或多个单词与目标匹配。

另一个问题:

anyRobotSeen = false
for rs in r:
  if (CI(rs, "robot")) then:
    anyRobotSeen = true
    if (CS(rs, "robot")) then print "small robot"
    elif (CS(rs, "ROBOT")) then print "big robot"
    else print "medium robot"
if (anyRobotSeen == false) then print "no robots on this line"
转化为

rs[0] == "r" or "R" and rs[1] == "o" or "O" and rs[2] == "b" or "B" and rs[3] == "O" or"o" and rs[-1] == "T" or "t"
它总是
True
,因为
“R”
的计算结果为真值。正确的语法是

(rs[0] == "r")
or 
"R" 
and 
(rs[1] == "o")
or 
"O"  # etc.
尽管这样做会容易得多

rs[0] in ("r", "R") and rs[1] in ("o", "O") and ...

您可能需要执行索引查找。这样你就不会多次寻找平等了

rs.lower() == "robot"
它可能通过减少if语句的数量来节省可读性。如果您真的想创建一些枚举类,也可以创建一些枚举类,但只有在多次检查该类的情况下才能创建

rs.lower() == "robot"
由于您知道所有可能的结果,因此可以轻松创建主列表

rl = ["robot", "ROBOT"]
r = input()
idx = rl.index(r)
if idx == 0:
    robot = "little"
elif idx == 1:
    robot = "big"
...

添加语言标签。rs可能有不同的长度,例如,如果rs有两个字母,则没有rs[3]谢谢-我不知道.istitle-这可能会派上用场!
ROBOT = "robot"
rl = [ROBOT, ROBOT.title(), ROBOT.capitalize()] # Look at .casefold() too