python - 如何将随机字符中的字符串与列表连接起来?
问题描述
我有这个脚本可以从 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))
而是使用特殊字符列表,但这也不起作用。
解决方案
不确定您希望最终输出是什么,但请尝试:
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]}"
推荐阅读
- javascript - 在 JavaScript 中写 (a&b)<<1 而不是 (a&b)*2 更传统吗?
- javascript - 根据版本号排序表
- google-maps - 无法从方法中获取对作用域变量的引用
- python - 正则表达式严格匹配具有不同结尾的两行
- c# - 创建自定义权限级别
- c# - 如何获取和设置checkedlistbox数据,无论其绑定内容是否来自列表本身
- apache - 让我们加密 Raspberry Pi 拉伸不起作用
- tfs - TFS 2018 - 无法使用搜索功能
- python - 为 TensorFlow 安装 Bazel 的问题
- twilio - 我可以连接我的 IBM Cloudant 数据库作为我的 Twilio IBM STT 附加服务的回调 URL 吗?