Python | Scramble strings in a list



Method # 1: Using List Comprehension + sample () + join ()
A combination of the above functions can be used to solve this problem. In this case, we need to split the string into a list of characters, scramble them with sample (), concatenate them with join (), and then rewrite the list using a list comprehension.

# Python3 code to demonstrate how it works
# Scramble lines in a list
# using a list comprehension + sample () + join ()

from random import sample 

  
# initialize the list

test_list = [ `gfg` , ` is` , `best` , ` for` , `geeks` ]

  
# print original list

print ( "The original list:" + str (test_list))

 
# Scramble lines in the list
# using a list comprehension + sample () + join ()

res = [`` .join (sample (ele, len (ele))) for ele i n test_list]

 
# print result

print ( " Scrambled strings in lists are: " + str (res))

Output:

 The original list: [`gfg`,` is`, `best`,` for`, `geeks`] Scrambled strings in lists are: [` fgg`, `is`,` btse`, `rof`,` sgeke`]  

Method # 2: Using comprehension list + shuffle () + join ()
This is similar to the above method. The only difference is that shuffle () is used to perform the scrambling task, rather than sample () is used.

# Python3 code to demonstrate how it works
# Scramble lines in the list
# use comprehension list + shuffle () + join ()

from random import shuffle

 
# Helper function

def perform_scramble (ele):

  ele = list (ele)

  shuffle (ele)

return `` .join (ele)

 
# initialize the list

test_list = [ `gfg` , `is` , ` best` , `for` , ` geeks` ]

 
# print original list

print ( "The original list:" + str (test_list))

  
# Scramble lines in the list
# use comprehension list + shuffle () + join ()

res = [perform_scramble (ele) for ele in test_list]

 
# print result

print ( "Scrambled strings in lists are:" + str (res))

Output:

 The original list: [`gfg`,` is`, `best`,` for`, `geeks`] Scrambled strings in lists are: [`fgg`,` is`, `btse`,` rof`, `sgeke`]