Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert random characters in a string to uppercase

Tags:

python

I'm try to append text strings randomly so that instead of just having an output like

>>>david

I will end up having something like

>>>DaViD
>>>dAviD

the code i have right now is this

import random
import string

print "Name Year"
text_file = open("names.txt", "r")
for line in text_file:
    print line.strip()+"".join([random.choice(string.digits) for x in range(1, random.randint(1,9))])

and it outports this

>>>JOHN01361

I want that string to be somthing like

>>>jOhN01361
>>>john01361
>>>JOHN01361
>>>JoHn01361
like image 955
user705260 Avatar asked Nov 05 '11 06:11

user705260


People also ask

How do you convert a string to uppercase?

JavaScript String toUpperCase() The toUpperCase() method converts a string to uppercase letters. The toUpperCase() method does not change the original string.

How can I convert each alternate character of a string to uppercase in C++?

You can convert a character to upper case using the toUpperCase() method of the character class.

How do you convert lowercase to uppercase?

To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.


2 Answers

Well, your specification is actually to randomly uppercase characters, and if you were so inclined, you could achieve that with the following list comprehension:

import random

s = "..."
s = "".join( random.choice([k.upper(), k ]) for k in s )

but there may be nicer ways ...

like image 100
Noon Silk Avatar answered Oct 22 '22 22:10

Noon Silk


you probably want to do something like:

import random

lol = "lol apples"

def randomupper(c):
    if random.random() > 0.5:
        return c.upper()
    return c.lower()

lol =''.join(map(randomupper, lol))

EDIT:

As pointed out by Shawn Chin in the comments, this can be simplified to:

lol = "".join((c.upper(), c)[random() > 0.5] for c in lol)

Very cool and, but slower than using map.


EDIT 2:

running some timer tests, it seems that
"".join( random.choice([k.upper(), k ]) for k in s )
is over 5 times slower than the map method, can anyone confirm this?
Times are:

no map:        5.922078471303955
map:           4.248832001003303
random.choice: 25.282491881882898
like image 1
Serdalis Avatar answered Oct 22 '22 21:10

Serdalis