python“递增”一个字符串?
我知道在java中,如果你有一个char变量,你可以执行以下操作:
char a = 'a'
a = a + 1
System.out.println(a)
这将打印'b'。我不知道这是什么的确切名称,但是有没有办法在 python 中做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 ord 和 chr :
有关 ord 和 chr。
You could use ord and chr :
More information about ord and chr.
作为替代方案,
如果您确实需要像示例中那样移动字母表,则可以使用
string.lowercase
并对其进行迭代:请参阅 http://docs.python.org/library/string.html#string-constants 了解更多
As an alternative,
if you actually need to move over the alphabet like in your example, you can use
string.lowercase
and iterate over that:see http://docs.python.org/library/string.html#string-constants for more
当 char 为 z 并且您将其增加 1 或 2 时,上述解决方案将不起作用,
示例:如果您将 z 增加 incr (假设 incr = 2 或 3),则 (chr(ord('z')+incr)) 不会给你增加的值,因为 ascii 值超出范围。
对于通用方式,您必须执行此操作,
它将适用于递增或递减两者。
对于大写字母也可以这样做,只是 asci 值会改变。
Above solutions wont work when char is z and you increment that by 1 or 2,
Example: if you increment z by incr (lets say incr = 2 or 3) then (chr(ord('z')+incr)) does not give you incremented value because ascii value goes out of range.
for generic way you have to do this
it will work for increment or decrement both.
same can be done for uppercase letter, only asci value will be changed.