[英]How do I move a specific part of a string to a new string
例如,假設我正在使用以下字符串
key = "XPMGTDHLYONZBWEARKJUFSCIQV"
example = "test"
newKey = ""
我想獲得該字符串的隨機部分,我知道長度。 所以
length = len(example)
rand = random.randint(0, len(key) - length)
我相信這段代碼將采用從0到鍵的長度減去示例的隨機數。 這應該確保我總是有足夠的字母。 我卡住的部分是如何獲取起點,rand和終點,長度,並使用它們來獲取密鑰的特定部分。 例如,假設rand = 2
和length = 4
。 那么newKey
應該是newKey = "MGTD"
。
我可以使用哪個字符串命令來獲得此結果?
您可以簡單地對密鑰進行切片:
newKey = key[rand:rand + length]
演示:
>>> length, rand = 4, 2
>>> key = "XPMGTDHLYONZBWEARKJUFSCIQV"
>>> key[rand:rand + length]
'MGTD'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.