Randomly selecting a character and 4 subsequent characters from a string
Question:
Given the following string
string = 'SATSUNMONTUEWEDTHUFRI'
If I wanted to randomly select a character/s I can accomplish that using random.choices()
For example, here I’m selecting 5 characters
rs = random.choices(string, k = 5)
But, what if I wanted to select 5 subsequent characters. One possible result is:
[SATSU]
How can I accomplish this?
Answers:
Select a random index between 0 and the 5th-to-last position of the string, then slice the string beginning from that position.
The solution to above explanation:
string = 'SATSUNMONTUEWEDTHUFRI'
x = random.randint(0, len(string)-5)
rs = string[x: x+5]
Given the following string
string = 'SATSUNMONTUEWEDTHUFRI'
If I wanted to randomly select a character/s I can accomplish that using random.choices()
For example, here I’m selecting 5 characters
rs = random.choices(string, k = 5)
But, what if I wanted to select 5 subsequent characters. One possible result is:
[SATSU]
How can I accomplish this?
Select a random index between 0 and the 5th-to-last position of the string, then slice the string beginning from that position.
The solution to above explanation:
string = 'SATSUNMONTUEWEDTHUFRI'
x = random.randint(0, len(string)-5)
rs = string[x: x+5]