Python - 字符串中的随机大写
给定一个字符串,任务是编写一个Python程序将其字符随机转换为大写。
例子:
Input : test_str = 'geeksforgeeks'
Output : GeeksfORgeeks
Explanation : Random elements are converted to Upper case characters.
Input : test_str = 'gfg'
Output : GFg
Explanation : Random elements are converted to Upper case characters.
方法 #1:使用join() + choice() + upper() + lower()
在这种情况下,我们在每个字符上使用 choice() 执行选择随机字符为大写的任务。 upper() 和lower() 分别执行大写和小写字符的任务。
Python3
# Python3 code to demonstrate working of
# Random uppercase in Strings
# Using join() + choice() + upper() + lower()
from random import choice
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# choosing from upper or lower for each character
res = ''.join(choice((str.upper, str.lower))(char) for char in test_str)
# printing result
print("Random Uppercased Strings : " + str(res))
Python3
# Python3 code to demonstrate working of
# Random uppercase in Strings
# Using map() + choice() + zip()
from random import choice
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# choosing from upper or lower for each character
# extending logic to each character using map()
res = ''.join(map(choice, zip(test_str.lower(), test_str.upper())))
# printing result
print("Random Uppercased Strings : " + str(res))
输出:
The original string is : geeksforgeeks
Random Uppercased Strings : gEEkSFoRgEeKS
方法#2:使用map() + choice() + zip()
在这里,我们在所有连接的小写和大写字符串的字符上暗示选择()(使用 zip()),使用 map()。
蟒蛇3
# Python3 code to demonstrate working of
# Random uppercase in Strings
# Using map() + choice() + zip()
from random import choice
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# choosing from upper or lower for each character
# extending logic to each character using map()
res = ''.join(map(choice, zip(test_str.lower(), test_str.upper())))
# printing result
print("Random Uppercased Strings : " + str(res))
输出:
The original string is : geeksforgeeks
Random Uppercased Strings : geEkSFORgEEKS