For example, let's say I am using the following strings
key = "XPMGTDHLYONZBWEARKJUFSCIQV"
example = "test"
newKey = ""
and I want to get a random section of that string and I know the length. So
length = len(example)
rand = random.randint(0, len(key) - length)
I believe this code will take a random number from 0 to the length of the key minus the example. This should insure that I always have enough letters. The part I am getting stuck on, is how I take the starting point, rand, and the ending point, length, and use them to get a specific part of the key. For example, let's say rand = 2
and length = 4
. Then newKey
should be, newKey = "MGTD"
.
What string command can I use to get this result?
You can simply slice the key:
newKey = key[rand:rand + length]
Demo:
>>> length, rand = 4, 2
>>> key = "XPMGTDHLYONZBWEARKJUFSCIQV"
>>> key[rand:rand + length]
'MGTD'
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.