首页 > 解决方案 > 如何将随机字符中的字符串与列表连接起来?

问题描述

我有这个脚本可以从 URL 中提取随机单词,并与存储在列表中的其他特殊字符连接:

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('[]'))

输出是这样的:'-', '@'auxiliary__2'-'.

问题是即使我使用.join我也无法摆脱''并将所有内容连接在一起。

我也尝试过:

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

而是使用特殊字符列表,但这也不起作用。

标签: pythonlistconcatenationstring-concatenation

解决方案


不确定您希望最终输出是什么,但请尝试:

random_num2 = [randint(0,10)][0]  

然后:

final_string = f"{''.join(map(str, special_char))}{words[random_num]}__{random_num2}{''.join(map(str, special_char2))}"

或者您可以通过索引获取特殊字符:

final_string = f"{''.join(map(str, special_char))}{words[random_num]}__{random_num2}{special_char2[0]}"

推荐阅读