Search code examples
pythonlistconcatenationstring-concatenation

How to concatenate strings from random character with list?


I have this script that picks up random words from an URL and it concatenates with other special characters stored in a list:

import requests
import random
from random import randint
import string

url = 'https://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain'
r = requests.get(url)

text = r.text
words = text.split()
random_num = randint(0, len(words))
random_num2 = [randint(0,10)]

special_list = ['#','!','@','-', '@']
union = "".join(str(x) for x in special_list)
special_char = random.choices(union, k=2)
special_char2 = random.choices(union)

final_string = (str(special_char).strip('[]') + words[random_num] + '__' + 
                str(random_num2).strip('[]') + str(special_char2).strip('[]'))

The output is something like that: '-', '@'auxiliary__2'-'.

The problem is even if I use .join I cannot get rid of '' and concatenate everything together.

I also tried with:

   random_char = ''.join(string.punctuation for i in range(0,1))

instead using a special character list, but also this didn't work.


Solution

  • random.choices gives you a list. You can access things in the list like so: special_char[0] instead of converting the list to a string and messing about with the string. That way, you won't get the apostrophes that you get in the string representation of a list. str(special_char) ==> ['-', '@'] (for example). If you do ", ".join(special_char), you just get -, @. If you don't want the comma in between, just "".join(special_char) gives -@.

    Also, random_num2 = [randint(0,10)] creates a list with just one number. If you want to access just the number in the list, you need random_num2[0]. Or you can convert them all to strings and use ",".join() just like we did for special_char

    random_num2_str = [str(num) for num in random_num2]
    special_char = random.choices(union, k=2) 
    special_char2 = random.choices(union)
    
    final_string = ", ".join(special_char) + words[random_num] + '__' + ", ".join(random_num2_str) + special_char2[0]
    

    Unless you really need random_num2 as a list, you should do random_num2 = randint(0,10). Then, you could do

    final_string = ", ".join(special_char) + words[random_num] + '__' + str(random_num2) + special_char2[0]