One way without involving python loop would be sending it to numpy and do vectorized operation over that. For example:
import numpy as np
def randomCapitalize(s):
s = np.array(s, 'c').view('u1')
t = np.random.randint(0, 2, len(s), 'u1') # Temporary array
t *= s != 32 # ASCII 32 (i.e. space) should not be lowercased
t *= 32 # Decrease ASCII by 32 to lowercase
s -= t
return s.view('S' + str(len(s)))[0]
randomCapitalize('hello world jfwojeo jaiofjowejfefjawivj a jofjawoefj')
which outputs:
b'HELLO WoRlD jFwoJEO JAioFjOWeJfEfJAWIvJ A JofjaWOefj'
This solution should be reasonably fast especially for long string. There are two limitations of this method:
The input must be fully lower case. You can try .lower()
it first but thats technically low efficient.
It need special care for non-a-to-z character. In the example above, only space is handled
You can handle a lot more special characters at the same time by replacing
t *= s != 32
with
# using space, enter, comma, period as example
t *= np.isin(s, list(map(ord, ' \n,.')), invert=True)
For example:
s = 'ascii table and description. ascii stands for american standard code for information interchange. computers can only understand numbers, so an ascii code is the numerical representation of a character such as'
randomCapitalize(s)
which outputs:
b'ascII tABLe AnD descRiptIOn. ascii sTaNds for AmEricAN stanDaRD codE FOr InForMAtION iNTeRCHaNge. ComPUtERS can onLY UNdersTand nUMBers, So An asCIi COdE IS tHE nuMERIcaL rEPrEsEnTATion Of a CHaractEr such as'