{"id":4008,"date":"2020-03-12T19:23:18","date_gmt":"2020-03-12T19:23:18","guid":{"rendered":"https:\/\/www.askpython.com\/?p=4008"},"modified":"2023-02-16T19:57:13","modified_gmt":"2023-02-16T19:57:13","slug":"generate-random-strings-in-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/generate-random-strings-in-python","title":{"rendered":"How to Generate Random Strings in Python"},"content":{"rendered":"\n<p>In this article, we&#8217;ll take a look at how we can generate random strings in Python. As the name suggests, we need to generate a random sequence of characters, it is suitable for the <code>random<\/code> module.<\/p>\n\n\n\n<p>There are various approaches here, so we&#8217;ll start from the most intuitive one; using randomized integers.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Build a string from a random integer sequence<\/h2>\n\n\n\n<p>As you may know, the <code>chr(integer)<\/code> maps the integer to a character, assuming it lies within the ASCII limits. (Taken to be <code>255<\/code> for this article)<\/p>\n\n\n\n<p>We can use this mapping to scale any integer to the ASCII character level, using <code>chr(x)<\/code>, where <code>x<\/code> is generated randomly.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport random\n\n# The limit for the extended ASCII Character set\nMAX_LIMIT = 255\n\nrandom_string = &#039;&#039;\n\nfor _ in range(10):\n    random_integer = random.randint(0, MAX_LIMIT)\n    # Keep appending random characters using chr(x)\n    random_string += (chr(random_integer))\n\nprint(random_string, len(random_string))\n\n<\/pre><\/div>\n\n\n<p><strong>Sample Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n\u00f0|\u00d2R:\n     R\u00e8 10\n<\/pre><\/div>\n\n\n<p>Here, while the length of the string seems to be 10 characters, we get some weird characters along with newlines, spaces, etc.<\/p>\n\n\n\n<p>This is because we considered the entire ASCII Character set.<\/p>\n\n\n\n<p>If we want to deal with only English alphabets, we can use their ASCII values.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport random\n\nrandom_string = &#039;&#039;\n\nfor _ in range(10):\n    # Considering only upper and lowercase letters\n    random_integer = random.randint(97, 97 + 26 - 1)\n    flip_bit = random.randint(0, 1)\n    # Convert to lowercase if the flip bit is on\n    random_integer = random_integer - 32 if flip_bit == 1 else random_integer\n    # Keep appending random characters using chr(x)\n    random_string += (chr(random_integer))\n\nprint(random_string, len(random_string))\n\n<\/pre><\/div>\n\n\n<p><strong>Sample Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nwxnhvYDuKm 10\n<\/pre><\/div>\n\n\n<p>As you can see, now we have only upper and lowercase letters.<\/p>\n\n\n\n<p>But we can avoid all this hassle, and have Python do the work for us. Python has given us the <code>string<\/code> module for exactly this purpose!<\/p>\n\n\n\n<p>Let&#8217;s look at how we can do the same this, using just a couple of lines of code!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Generate Random Strings in Python using the string module<\/h2>\n\n\n\n<p>The list of characters used by <a href=\"https:\/\/www.askpython.com\/python\/string\/python-string-functions\" class=\"rank-math-link\">Python strings<\/a> is defined here, and we can pick among these groups of characters.<\/p>\n\n\n\n<p>We&#8217;ll then use the <code>random.choice()<\/code> method to randomly choose characters, instead of using integers, as we did previously.<\/p>\n\n\n\n<p>Let us define a function <code>random_string_generator()<\/code>, that does all this work for us. This will generate a random string, given the length of the string, and the set of allowed characters to sample from.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport random\nimport string\n\ndef random_string_generator(str_size, allowed_chars):\n    return &#039;&#039;.join(random.choice(allowed_chars) for x in range(str_size))\n\nchars = string.ascii_letters + string.punctuation\nsize = 12\n\nprint(chars)\nprint(&#039;Random String of length 12 =&#039;, random_string_generator(size, chars))\n<\/pre><\/div>\n\n\n<p>Here, we have specified the allowed list of characters as the <code>string.ascii_letters<\/code> (upper and lowercase letters), along with <code>string.punctuation<\/code> (all punctuation marks).<\/p>\n\n\n\n<p>Now, our main function was only 2 lines, and we could randomly choose a character, using <code>random.choice(set)<\/code>.<\/p>\n\n\n\n<p><strong>Sample Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!&quot;#$%&amp;&#039;()*+,-.\/:;&lt;=&gt;?@&#x5B;\\]^_`{|}~\nRandom String of length 12 = d&#x5B;$Om{;#cjue\n<\/pre><\/div>\n\n\n<p>We have indeed generated a random string, and the <code>string<\/code> module allows easy manipulations between character sets!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Make the random generation more secure<\/h3>\n\n\n\n<p>While the above random generation method works, if you want to make your function be more cryptographically secure, use the <code>random.SystemRandom()<\/code> function.<\/p>\n\n\n\n<p>An example random generator function is shown below:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport random\nimport string\n\noutput_string = &#039;&#039;.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(10))\n\nprint(output_string)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\niNsuInwmS8\n<\/pre><\/div>\n\n\n<p>This ensures that your string generation is cryptographically secure.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Random UUID Generation<\/h2>\n\n\n\n<p>If you want to generate a random <a class=\"rank-math-link rank-math-link\" href=\"https:\/\/en.wikipedia.org\/wiki\/Universally_unique_identifier\" target=\"_blank\" rel=\"noopener\">UUID<\/a> String, the <code>uuid<\/code> module is helpful for this purpose.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport uuid\n\n# Generate a random UUID\nprint(&#039;Generated a random UUID from uuid1():&#039;, uuid.uuid1())\nprint(&#039;Generated a random UUID from uuid4():&#039;, uuid.uuid4())\n<\/pre><\/div>\n\n\n<p><strong>Sample Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nGenerated a random UUID from uuid1(): af5d2f80-6470-11ea-b6cd-a73d7e4e7bfe\nGenerated a random UUID from uuid4(): 5d365f9b-14c1-49e7-ad64-328b61c0d8a7\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we learned how we could generate random strings in Python, with the help of the <code>random<\/code> and <code>string<\/code> modules.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>JournalDev article on generating random strings<\/li><li><a href=\"https:\/\/stackoverflow.com\/questions\/2257441\/random-string-generation-with-upper-case-letters-and-digits\" class=\"rank-math-link\" target=\"_blank\" rel=\"noopener\">StackOverflow question<\/a> on random string generation<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we&#8217;ll take a look at how we can generate random strings in Python. As the name suggests, we need to generate a random sequence of characters, it is suitable for the random module. There are various approaches here, so we&#8217;ll start from the most intuitive one; using randomized integers. Build a string [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":4024,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-4008","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/4008","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=4008"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/4008\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/4024"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=4008"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=4008"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=4008"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}