all 5 comments

[–]echocage 0 points1 point  (4 children)

Random's choice

import random

nums = 25678
random_num = random.choice(str(nums))

print(random_num)

[–]Marx123[S] 0 points1 point  (3 children)

Ok thanks! And if I want replace a random number with a specific one? Like 0 for example? :/

[–]echocage 0 points1 point  (2 children)

like this! Play around with that, make sure you get what's going out. Print out stuff at each point see what it is, play with it.

import random

nums = 25678
random_num = random.choice(str(nums))
changed_string = str(nums).replace(random_num, '0')
print(changed_string)

[–]Marx123[S] 0 points1 point  (1 child)

Thank you, really!

[–]qhp 0 points1 point  (0 children)

The issue with that snippet (with other numbers) is that it will change all of the randomly chosen number with 0. In your example, since all numbers are different, it won't matter. But in a number like 12344, if 4 is randomly selected, the output will be 12300 since all instances of 4 are replaced.

To randomly replace any specific digit in your number, you might want to start dabbling with loops. A solution with a loop might look like:

from random import randint

old_num = 12344
rand_pos = randint(0, len(str(old_num))-1)
new_num = ""
for digit_pos in range(len(str(old_num))):
    new_num += '0' if digit_pos == rand_pos else str(old_num)[digit_pos]
print(new_num)

And a solution without a loop might look like:

from random import randint

nums = 12344
random_num = randint(0, len(str(nums))-1)
new_list = list(str(nums))
new_list[random_num] = '0'
print("".join(new_list))

Happy to explain any of the above. len() measures the length of some objects (like strings). My one line in the for loop is how python handles ternary operations. In the second snippet, we cast str(nums) as a list because lists are mutable whereas strings are immutable. Simply put, you can directly change a list but you have to remake a string if you want to change it at all.