Reputation: 53
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.
Upvotes: 0
Views: 1003
Reputation: 11360
Not sure exactly what you want the final output to be, but try:
random_num2 = [randint(0,10)][0]
then:
final_string = f"{''.join(map(str, special_char))}{words[random_num]}__{random_num2}{''.join(map(str, special_char2))}"
or you can get special characters by index:
final_string = f"{''.join(map(str, special_char))}{words[random_num]}__{random_num2}{special_char2[0]}"
Upvotes: 1
Reputation: 25489
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]
Upvotes: 0