問題描述
我是 Python 的新手,來自 Java 和 C.如何增加 char?在 Java 或 C 中,chars 和 int 實際上是可以互換的,并且在某些循環中,能夠對 chars 進行增量以及按 chars 索引數組對我非常有用.
I'm new to Python, coming from Java and C. How can I increment a char? In Java or C, chars and ints are practically interchangeable, and in certain loops, it's very useful to me to be able to do increment chars, and index arrays by chars.
如何在 Python 中做到這一點?沒有傳統的 for(;;) 循環器已經夠糟糕了 - 有什么方法可以實現我想要實現的目標,而無需重新考慮我的整個策略?
How can I do this in Python? It's bad enough not having a traditional for(;;) looper - is there any way I can achieve what I want to achieve without having to rethink my entire strategy?
推薦答案
在 Python 2.x 中,只需使用 ord
和 chr
函數:
In Python 2.x, just use the ord
and chr
functions:
>>> ord('c')
99
>>> ord('c') + 1
100
>>> chr(ord('c') + 1)
'd'
>>>
Python 3.x 使這更加有條理和有趣,因為它在字節和 unicode 之間有明顯的區別.默認情況下,字符串"是 unicode,因此上述方法有效(ord
接收 Unicode 字符,chr
生成它們).
Python 3.x makes this more organized and interesting, due to its clear distinction between bytes and unicode. By default, a "string" is unicode, so the above works (ord
receives Unicode chars and chr
produces them).
但是如果你對字節感興趣(比如處理一些二進制數據流),事情就更簡單了:
But if you're interested in bytes (such as for processing some binary data stream), things are even simpler:
>>> bstr = bytes('abc', 'utf-8')
>>> bstr
b'abc'
>>> bstr[0]
97
>>> bytes([97, 98, 99])
b'abc'
>>> bytes([bstr[0] + 1, 98, 99])
b'bbc'
這篇關于我怎樣才能增加一個字符?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!