Random String Generator with Python

  • Share this:

Code introduction


This function generates a random string of a specified length using the `random` and `string` libraries to create random characters and then concatenates them into a string.


Technology Stack : random, string

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import string
import re
import math
import sys
import os

def generate_random_string(length=10):
    letters = string.ascii_letters
    return ''.join(random.choice(letters) for i in range(length))

def remove_non_ascii(text):
    return re.sub(r'[^\x20-\x7E]+', '', text)

def calculate_circumference(radius):
    return 2 * math.pi * radius

def print_to_file(filename, text):
    with open(filename, 'w') as file:
        file.write(text)

def list_files_in_directory(directory):
    return [file for file in os.listdir(directory) if os.path.isfile(os.path.join(directory, file))]                
              
Tags: