如何增加一个字符? [英] How can I increment a char?

查看:122
本文介绍了如何增加一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,来自Java和C。如何增加一个字符?在Java或C语言中,char和int实际上是可以互换的,并且在某些循环中,能够递增char并按char索引数组对我来说非常有用。

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'

这篇关于如何增加一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆