如何从python中的字符串生成随机值?

时间:2018-09-07 07:36:48

标签: python random

我有一个字符串-- phpMyAdmin SQL Dump -- version 4.8.2 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: Sep 08, 2018 at 11:38 AM -- Server version: 10.1.34-MariaDB -- PHP Version: 7.2.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `mydb` -- -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE `products` ( `id` int(11) NOT NULL, `product_Image` varchar(128) NOT NULL, `product_name` varchar(255) NOT NULL, `date_uploaded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Indexes for dumped tables -- -- -- Indexes for table `products` -- ALTER TABLE `products` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `products` -- ALTER TABLE `products` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; ,我希望每次运行程序时随机生成4个 unique 字符。

结果应为:

我可以使用'ABCDEF',但需要使用BDAF EDCB CAFE ... ,是否有使用random.sample来达到相同结果的方法?

4 个答案:

答案 0 :(得分:2)

您可以使用Python的random模块提供的功能。 使用random.sample从字符串中提取随机的字符集,然后join将它们提取:

import random
source = "ABCDEFG"
result = "".join(random.sample(source, 4))

答案 1 :(得分:0)

您确实可以使用random.sample;它会给您一个列表,但将结果列表连接到字符串中很容易:

result = ''.join(random.sample("ABCDEF", 4))

答案 2 :(得分:0)

您可以使用random进行此操作,然后将结果列表与''一起创建一个字符串:

import random
c = "ABCDEF"
''.join(random.sample(c, 4))

对于输入,您可以像在Python中那样使用字符串,字符串也是列表(字符列表)

答案 3 :(得分:-1)

有3种解决方案(可能还有100种):

  1. “经典” for方法将每个N=4字母附加到同一字符串,以及choice模块的random方法中选择一个元素

  2. 使用join methodchoices模块的random方法生成的元素一次性添加。 choices方法用途广泛,可以与多个参数(official documentation)一起使用,

  3. 使用join methodsample模块的random方法生成的元素一次性添加。 sample(set,num)方法随机选择num中的set个元素。


import random
N=4
source_string = 'ABCDEF

Method1

random_string_1=""
for it in range(0,N):
    random_string_1 = random_string_1 + random.choice(source_string)

Method2

random_string_2 = "".join(random.choices(source_string, weights=None, 
cum_weights=None, k=N))

Method3

random_string_3 = "".join(random.sample(source_string, N))