简体   繁体   中英

How to return both an int and a number in python use chr and ord?

I'm very new to this so have mercy on my poor, stupid soul.

If you wanted to return a two-character ".com" with both a string and a string-and-a-string and a string and an int (ie: "ab.com" and "a7.com") how would you do it?

I've been looking at other code and I'm literally getting Japanese characters returned.

while letter1 <= 'z': # Outer loop
letter2 = 'a'
   while letter2 <= 'z': # Inner loop
        print('%s%s.com' % (letter1, letter2))
        letter2 = chr(ord(letter2) + 1)
        letter1 = chr(ord(letter1) + 1)

letter2 should be returning either a letter az or a number but it only gives me back whatever letter1 is ('aa, bb, cc, etc...')

If I understand what you're looking for, you can use itertools.product to generate this:

First, generate your alphabet. For this, I'm going to use alphabet = string.ascii_lowercase + string.digits (in other words, az and 0-9).

If I say: list(itertools.product(alphabet, repeat=2)) , we start getting what we're looking for:

[('a', 'a'), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('a', 'f'), ('a', 'g'), ...]

So for example, your entire code could look like:

def domain_generator(alphabet, length, suffix):
    for first, second in itertools.product(alphabet, repeat=length):
        yield '{}{}.{suffix}'.format(first, second, suffix=suffix)

where you can now iterate over the domain generator with:

for domain in domain_generator(string.ascii_lowercase + string.digits, 2, 'com'):
    print(domain)

Sounds like what you want is basically a list of all domains matching the regex [a-z0-9][a-z0-9].com .

Fiddling with the ASCII character value could be one way to implement this, but I think it would be more pythonic to try something like this instead:

import string
for letter1 in string.ascii_lowercase+string.digits:
  for letter2 in string.ascii_lowercase+string.digits:
     print('%s%s.com' % (letter1, letter2))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM