2010-11-14 43 views
3

我知道在Java中,如果你有一個char變量,你可以做到以下幾點:python「遞增」一個字符串?

char a = 'a' 
a = a + 1 
System.out.println(a) 

這將打印「B」。我不知道這是什麼的確切名稱,但有什麼辦法可以在Python中做到這一點?

+2

在Java中,char值與無符號的16位整數基本相同。所以,增加它實際上只是增加它。但是,Python不會將字符與整數交換。 – 2010-11-14 19:29:59

+1

爲了闡述格雷格說的話,你會如何增加「我是一個字符串」?因爲這就是Python中'char'的意思:恰好具有長度爲1的字符串。 – aaronasterling 2010-11-14 19:35:10

+0

[Python:我如何增加一個字符?](http://stackoverflow.com/questions/2156892/python- how-can-i-increment-a-char) – outis 2016-02-14 00:58:18

回答

13

你可以使用Ord和CHR:

print(chr(ord('a')+1)) 
# b 

更多有關ordchr

+0

非常感謝。 – Trim 2010-11-14 19:33:45

0

上述解決方案不會工作時,字符是z,你增加了1或2,

例如:如果你有(incr = 2或3)然後(chr(ord('z')+ incr))不會給你遞增的值,因爲ascii值超出範圍。

爲通用的方法,你必須這樣做

i = a to z any character 
incr = no. of increment 
#if letter is lowercase 
asci = ord(i) 
if (asci >= 97) & (asci <= 122):    
    asci += incr 
    # for increment case 
    if asci > 122 : 
    asci = asci%122 + 96 
    # for decrement case 
    if asci < 97: 
     asci += 26 
    print chr(asci) 

它將爲增量工作或減少兩者。

對於大寫字母可以做同樣的事情,只有asci值會被改變。