import random
for i in range(1):
myNum= str(random.randint(1,5))
print(myNum)
Wanted to replace every occurrence of the number 1 with the letter j in python, how would one go about doing this?
Another option is to just select from the options you want in the first place:
myNum = random.choice(('j', '2', '3', '4', '5'))
# Equivalently, assuming they're all one character values:
myNum = random.choice('j2345')
Might even run a touch faster, since there are no type conversions needed (and a tuple
of literal constants is cached in the function/module constants at least on CPython, so it won't be reconstructed over and over).
So long as it is just a single character from a string length up to 9, you can do:
my_chr='j2345'[random.randint(0,4)]
Just make sure that the string is the same length as the potential range of the random int.
Just use an if statement:
import random
for i in range(1):
myNum = random.randint(1, 5)
if myNum == 1:
print("j")
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.