Xaqron
Xaqron

Reputation: 30837

concatenating character and number as one string

I wanna make strings like A1, A2... here is my code:

def random_room(self):
        return chr(random.randint(65, 90)) + chr(random.randint(1, len(self.rooms)))

but it doesn't work

Upvotes: 0

Views: 35

Answers (3)

chepner
chepner

Reputation: 531055

There are better abstractions available than using chr to manipulate low-level encodings.

You want to choose a capital letter

import string
from random import choice, randint

letter = choice(string.ascii_uppercase)

and an integer

number = randint(1, len(self.rooms))

then combine them into a single string

room = f'{letter}{number}'

Put it all together:

import string
from random import choice, randint


def random_room(self):
    letter = choice(string.ascii_uppercase)
    number = randint(1, len(self.rooms))
    return f'{letter}{number}'

Upvotes: 1

Jenia
Jenia

Reputation: 414

Use str instead of chr.

return str(random.randint(65, 90)) + str(random.randint(1, len(self.rooms)))

But I think you're trying to do something like this:

letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
id = 0 # Your number here
number = letters[id] + str(random.randint(1, ...))

Upvotes: 0

Claude Shannon
Claude Shannon

Reputation: 69

I would have do something like:

def random_room(self):
        return "{}{}".format(chr(random.randint(65, 90)), random.randint(1, len(self.rooms)+1))

so you will have a random letter followed by a number between 1 and len(self.rooms)

Upvotes: 0

Related Questions