简体   繁体   English

如何比较字符字符串

[英]How to compare Char Strings

So I'm trying to find the least/smallest char in a string. 所以我试图找到字符串中最小/最小的字符。 The program is suppose to compare each character to each other and finds the smallest char. 该程序假定将每个字符相互比较并找到最小的字符。 Should look like this when calling. 调用时应如下所示。

least("rcDefxB")
The least char is B

this is the code that i have so far 这是我到目前为止的代码

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)

but the output that i get is this: 但是我得到的输出是这样的:

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

I probably incremented the wrong way or compared my characters the wrong way. 我可能增加了错误的方式,或者以错误的方式比较了我的角色。 I feel like i have the right setup, let me know where i missed up in my code. 我觉得我的设置正确,让我知道我在代码中错过了什么。

You could just use : 您可以使用:

min("rcDefxB")

If you really want to write it on your own, you could use : 如果您真的想自己编写,可以使用:

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

Both methods require a non-empty string. 这两种方法都需要一个非空字符串。

Eric Duminil solution is better, but if you want your code works properly you should modify it as follows: 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)

if by smallest you mean the ASCII code position just: 如果最小的意思是ASCII代码位置只是:

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

but if you mean the alphabet position ignore the upper or lower case: 但是如果您的意思是字母位置,请忽略大小写:

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

Please consider the following approach: 请考虑以下方法:

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

After running least("rcDefxB") , you'll have: 运行least("rcDefxB") ,您将拥有:

The leastchar is B

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

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