Python - Random uppercase in Strings

Python - Random uppercase in Strings

Creating a tutorial to write a Python program that randomly uppercases characters in a string:

Objective: Given a string, randomly transform some of its characters to uppercase.

Example:

Input: "hello world" Possible output: "hEllO wOrld" 

Step-by-step Solution:

Step 1: Import necessary libraries.

import random 

Step 2: Define the input string.

input_string = "hello world" 

Step 3: Create a function to perform random uppercasing.

def random_uppercase(s): # Convert the string to a list of characters for mutability chars = list(s) # Decide for each character if it should be uppercased for i, char in enumerate(chars): if random.choice([True, False]): chars[i] = char.upper() # Convert the list of characters back to a string return ''.join(chars) 

Step 4: Call the function and display the modified string.

modified_string = random_uppercase(input_string) print(modified_string) 

Complete Program:

import random def random_uppercase(s): # Convert the string to a list of characters for mutability chars = list(s) # Decide for each character if it should be uppercased for i, char in enumerate(chars): if random.choice([True, False]): chars[i] = char.upper() # Convert the list of characters back to a string return ''.join(chars) # Define the input string input_string = "hello world" # Call the function and display the result modified_string = random_uppercase(input_string) print(modified_string) 

Possible Output:

HeLlO wOrlD 

Note: The output will differ each time you run the program since the uppercase transformations are random.

This tutorial provides an approach to randomly uppercase characters in a string. Using Python's built-in string methods and the random.choice() function, you can easily introduce random modifications into textual data.


More Tags

selectize.js unzip android-widget setinterval device-admin tidytext gradle-properties ignore-case rest-assured ion-select

More Programming Guides

Other Guides

More Programming Examples