[英]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.