繁体   English   中英

如何比较字符字符串

[英]How to compare Char Strings

所以我试图找到字符串中最小/最小的字符。 该程序假定将每个字符相互比较并找到最小的字符。 调用时应如下所示。

least("rcDefxB")
The least char is B

这是我到目前为止的代码

def least(inputS):
for i in range(len(inputS)-1):
    current = inputS[i]
    nextt = inputS[i+1]
    if current > nextt:
        current = nextt
        nextt = inputS[i+2]
        print('The least char is',current)

但是我得到的输出是这样的:

least("rcDefxB")
C
D
IndexError: string index out of range
in line least nextt = inputS[i+2]

我可能增加了错误的方式,或者以错误的方式比较了我的角色。 我觉得我的设置正确,让我知道我在代码中错过了什么。

您可以使用:

min("rcDefxB")

如果您真的想自己编写,可以使用:

def leastChar(inputString):
  min_char = inputString[0]
  for char in inputString:
    if char < min_char:
      min_char = char
  print 'The leastchar is %s' % min_char

这两种方法都需要一个非空字符串。

Eric Duminil解决方案更好,但是如果您希望代码正常运行,则应按以下方式进行修改:

inputString = "rcDefxB"
index = 0
while index < len(inputString) - 1:
    currentChar = inputString[index]
    nextChar = inputString[index + 1]
    if currentChar > nextChar:
        currentChar = nextChar
    index += 1
print('The leastchar is',currentChar)

如果最小的意思是ASCII代码位置只是:

>>> s = "aBCdefg"
>>> min(s)
'B'

但是如果您的意思是字母位置,请忽略大小写:

>>> min(s, key=lambda x: x.upper())
'a'

请考虑以下方法:

def least(inputString):
    leastChar = min(list(inputString))
    print('The leastchar is', leastChar)

运行least("rcDefxB") ,您将拥有:

The leastchar is B

暂无
暂无

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

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