我知道在Java中,如果你有一個char變量,你可以做到以下幾點:python「遞增」一個字符串?
char a = 'a'
a = a + 1
System.out.println(a)
這將打印「B」。我不知道這是什麼的確切名稱,但有什麼辦法可以在Python中做到這一點?
我知道在Java中,如果你有一個char變量,你可以做到以下幾點:python「遞增」一個字符串?
char a = 'a'
a = a + 1
System.out.println(a)
這將打印「B」。我不知道這是什麼的確切名稱,但有什麼辦法可以在Python中做到這一點?
作爲替代,
,如果你確實需要在字母表移動,就像在你的榜樣,您可以使用string.lowercase
和迭代是:
from string import lowercase
for a in lowercase:
print a
看到http://docs.python.org/library/string.html#string-constants更多
上述解決方案不會工作時,字符是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值會被改變。
在Java中,char值與無符號的16位整數基本相同。所以,增加它實際上只是增加它。但是,Python不會將字符與整數交換。 – 2010-11-14 19:29:59
爲了闡述格雷格說的話,你會如何增加「我是一個字符串」?因爲這就是Python中'char'的意思:恰好具有長度爲1的字符串。 – aaronasterling 2010-11-14 19:35:10
[Python:我如何增加一個字符?](http://stackoverflow.com/questions/2156892/python- how-can-i-increment-a-char) – outis 2016-02-14 00:58:18