简体   繁体   中英

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:

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:

>>> 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:

The leastchar is B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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