标签归档:char

如何增加一个字符?

问题:如何增加一个字符?

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

如何在Python中执行此操作?没有传统的for(;;)循环程序就够了-我有什么方法可以在不重新考虑整个策略的情况下实现我想要的目标?

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.

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?


回答 0

在Python 2.x中,只需使用ordchr函数:

>>> ord('c')
99
>>> ord('c') + 1
100
>>> chr(ord('c') + 1)
'd'
>>> 

Python 3.x使得字节和unicode之间有明显的区别,这使它变得更有条理和有趣。默认情况下,“字符串”是unicode,因此上面的方法有效(ord接收Unicode字符并chr产生它们)。

但是,如果您对字节感兴趣(例如用于处理某些二进制数据流),那么事情就更简单了:

>>> 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'

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 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'

回答 1

“足够糟糕,没有传统的for(;;)循环程序”?什么?

你想做吗

import string
for c in string.lowercase:
    ...do something with c...

也许您正在使用string.uppercasestring.letters

Python没有,for(;;)因为通常有更好的方法来执行它。它也没有字符数学,因为也没有必要。

“bad enough not having a traditional for(;;) looper”?? What?

Are you trying to do

import string
for c in string.lowercase:
    ...do something with c...

Or perhaps you’re using string.uppercase or string.letters?

Python doesn’t have for(;;) because there are often better ways to do it. It also doesn’t have character math because it’s not necessary, either.


回答 2

我来自PHP,您可以使用++运算符将char(A到B,Z到AA,AA到AB等)递增。我做了一个简单的函数,在Python中也是如此。您还可以将字符列表更改为您需要的任何字符(小写,大写等)。

# Increment char (a -> b, az -> ba)
def inc_char(text, chlist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
    # Unique and sort
    chlist = ''.join(sorted(set(str(chlist))))
    chlen = len(chlist)
    if not chlen:
        return ''
    text = str(text)
    # Replace all chars but chlist
    text = re.sub('[^' + chlist + ']', '', text)
    if not len(text):
        return chlist[0]
    # Increment
    inc = ''
    over = False
    for i in range(1, len(text)+1):
        lchar = text[-i]
        pos = chlist.find(lchar) + 1
        if pos < chlen:
            inc = chlist[pos] + inc
            over = False
            break
        else:
            inc = chlist[0] + inc
            over = True
    if over:
        inc += chlist[0]
    result = text[0:-len(inc)] + inc
    return result

I came from PHP, where you can increment char (A to B, Z to AA, AA to AB etc.) using ++ operator. I made a simple function which does the same in Python. You can also change list of chars to whatever (lowercase, uppercase, etc.) is your need.

# Increment char (a -> b, az -> ba)
def inc_char(text, chlist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
    # Unique and sort
    chlist = ''.join(sorted(set(str(chlist))))
    chlen = len(chlist)
    if not chlen:
        return ''
    text = str(text)
    # Replace all chars but chlist
    text = re.sub('[^' + chlist + ']', '', text)
    if not len(text):
        return chlist[0]
    # Increment
    inc = ''
    over = False
    for i in range(1, len(text)+1):
        lchar = text[-i]
        pos = chlist.find(lchar) + 1
        if pos < chlen:
            inc = chlist[pos] + inc
            over = False
            break
        else:
            inc = chlist[0] + inc
            over = True
    if over:
        inc += chlist[0]
    result = text[0:-len(inc)] + inc
    return result

回答 3

有一种使用ascii_lettersfrom string包增加字符的方法,该包ascii_letters是一个包含所有英文字母,大写和小写字母的字符串:

>>> from string import ascii_letters
>>> ascii_letters[ascii_letters.index('a') + 1]
'b'
>>> ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

也可以手动完成;

>>> letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> letters[letters.index('c') + 1]
'd'

There is a way to increase character using ascii_letters from string package which ascii_letters is a string that contains all English alphabet, uppercase and lowercase:

>>> from string import ascii_letters
>>> ascii_letters[ascii_letters.index('a') + 1]
'b'
>>> ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

Also it can be done manually;

>>> letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> letters[letters.index('c') + 1]
'd'

回答 4

检查一下:使用循环

for a in range(5): x='A' val=chr(ord(x)+a) print(val)
输出:ABCBDE

Check this: USING FOR LOOP

for a in range(5):
    x='A'
    val=chr(ord(x) + a)
    print(val)

LOOP OUTPUT: A B C D E


回答 5

def doubleChar(str):
    result = ''
    for char in str:
        result += char * 2
    return result

print(doubleChar("amar"))

输出:

aammaarr
def doubleChar(str):
    result = ''
    for char in str:
        result += char * 2
    return result

print(doubleChar("amar"))

output:

aammaarr

如何在Python中将字符转换为整数,反之亦然?

问题:如何在Python中将字符转换为整数,反之亦然?

我想要获得一个角色的ASCII价值。

例如,对于角色a,我要获取97,反之亦然。

I want to get, given a character, its ASCII value.

For example, for the character a, I want to get 97, and vice versa.


回答 0

使用chr()ord()

>>> chr(97)
'a'
>>> ord('a')
97

Use chr() and ord():

>>> chr(97)
'a'
>>> ord('a')
97

回答 1

>>> ord('a')
97
>>> chr(97)
'a'
>>> ord('a')
97
>>> chr(97)
'a'

回答 2

ord和chr