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
CodePudding user response:
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}'
CodePudding user response:
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)
CodePudding user response:
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, ...))