简体   繁体   English

如何将字符串的特定部分移至新字符串

[英]How do I move a specific part of a string to a new string

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. 我相信这段代码将采用从0到键的长度减去示例的随机数。 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. 我卡住的部分是如何获取起点,rand和终点,长度,并使用它们来获取密钥的特定部分。 For example, let's say rand = 2 and length = 4 . 例如,假设rand = 2length = 4 Then newKey should be, newKey = "MGTD" . 那么newKey应该是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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM