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?

Asked By: newbzzs

||

Answers:

Select a random index between 0 and the 5th-to-last position of the string, then slice the string beginning from that position.

Answered By: wim

The solution to above explanation:

string = 'SATSUNMONTUEWEDTHUFRI'

x = random.randint(0, len(string)-5)
rs = string[x: x+5]
Answered By: newbzzs
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.