English 中文(简体)
How can I increment a 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.

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?

最佳回答

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 
问题回答

"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.

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

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

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 
def doubleChar(str):
    result =   
    for char in str:
        result += char * 2
    return result

print(doubleChar("amar"))

output:

aammaarr

For me i made the fallowing as a test.

string_1="abcd"

def test(string_1):
   i = 0
   p = ""
   x = len(string_1)
   while i < x:
    y = (string_1)[i]
    i=i+1
    s = chr(ord(y) + 1)
    p=p+s

   print(p)

test(string_1)




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签