Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly capitalize letters in string [duplicate]

I want to randomly capitalize or lowercase each letter in a string. I'm new to working with strings in python, but I think because strings are immutable that I can't do the following:

i =0             
for c in sentence:
    case = random.randint(0,1)
    print("case = ", case)
    if case == 0:
        print("here0")
        sentence[i] = sentence[i].lower()
    else:
        print("here1")
        sentence[i] = sentence[i].upper()
    i += 1
print ("new sentence = ", sentence)

And get the error: TypeError: 'str' object does not support item assignment

But then how else could I do this?

like image 730
user1045890 Avatar asked Oct 23 '18 06:10

user1045890


People also ask

Why do I randomly write capital letters?

Usage and effect. Alternating caps are typically used to display mockery in text messages. The randomized capitalization leads to the flow of words being broken, making it harder for the text to be read as it disrupts word identification even when the size of the letters is the same as in uppercase or lowercase.

How do you randomize a capital letter in Python?

Here's a solution with little changes to your original code: >>> import random >>> >>> def randomcase(s): ...: result = '' ...: for c in s: ...: case = random. randint(0, 1) ...: if case == 0: ...: result += c. upper() ...: else: ...: result += c.

What is it called when random words are capitalized?

Studly caps is a form of text notation in which the capitalization of letters varies by some pattern, or arbitrarily (usually also omitting spaces between words and often omitting some letters), for example, StUdLyCaPs, STuDLyCaPS or sTuDLycApS. Such patterns are identified by many users, ambiguously, as camel case.

How do you capitalize every letter in a string?

Performing the . upper() method on a string converts all of the characters to uppercase, whereas the lower() method converts all of the characters to lowercase.


2 Answers

You can use str.join with a generator expression like this:

from random import choice
sentence = 'Hello World'
print(''.join(choice((str.upper, str.lower))(c) for c in sentence))

Sample output:

heLlo WORLd
like image 54
blhsing Avatar answered Oct 05 '22 04:10

blhsing


Build a new string.

Here's a solution with little changes to your original code:

>>> import random
>>> 
>>> def randomcase(s):
...:    result = ''
...:    for c in s:
...:        case = random.randint(0, 1)
...:        if case == 0:
...:            result += c.upper()
...:        else:
...:            result += c.lower()
...:    return result
...:
...:
>>> randomcase('Hello Stackoverflow!')
>>> 'hElLo StaCkoVERFLow!'

edit: deleted my oneliners because I like blhsing's better.

like image 21
timgeb Avatar answered Oct 05 '22 04:10

timgeb