python“递增”一个字符串?

发布于 2024-10-02 05:35:04 字数 165 浏览 0 评论 0 原文

我知道在java中,如果你有一个char变量,你可以执行以下操作:

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

这将打印'b'。我不知道这是什么的确切名称,但是有没有办法在 python 中做到这一点?

I know in java, if you have a char variable, you could do the following:

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

This would print 'b'. I don't know the exact name of what this is, but is there any way to do this in python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烟火散人牵绊 2024-10-09 05:35:04

您可以使用 ord 和 chr :

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

有关 ordchr

You could use ord and chr :

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

More information about ord and chr.

如梦亦如幻 2024-10-09 05:35:04

作为替代方案,

如果您确实需要像示例中那样移动字母表,则可以使用 string.lowercase 并对其进行迭代:

from string import lowercase

for a in lowercase:
    print a

请参阅 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:

from string import lowercase

for a in lowercase:
    print a

see http://docs.python.org/library/string.html#string-constants for more

樱桃奶球 2024-10-09 05:35:04

当 char 为 z 并且您将其增加 1 或 2 时,上述解决方案将不起作用,

示例:如果您将 z 增加 incr (假设 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 值会改变。

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

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)

it will work for increment or decrement both.

same can be done for uppercase letter, only asci value will be changed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文