Randomly capitalize letters in string
Clash Royale CLAN TAG#URR8PPP
up vote
7
down vote
favorite
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?
python python-3.x uppercase lowercase
add a comment |Â
up vote
7
down vote
favorite
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?
python python-3.x uppercase lowercase
Use another container, like alist
, then create the string from that. Alternatively, create a new sting incrementally
â juanpa.arrivillaga
8 hours ago
You can always create a new String with randomized caps and small letters.
â Mayank Porwal
8 hours ago
3
Possible duplicate of How do I modify a single character in a string, in Python?
â Sneftel
2 hours ago
add a comment |Â
up vote
7
down vote
favorite
up vote
7
down vote
favorite
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?
python python-3.x uppercase lowercase
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?
python python-3.x uppercase lowercase
python python-3.x uppercase lowercase
edited 12 mins ago
Konrad Rudolph
388k1007641015
388k1007641015
asked 8 hours ago
user1045890
574
574
Use another container, like alist
, then create the string from that. Alternatively, create a new sting incrementally
â juanpa.arrivillaga
8 hours ago
You can always create a new String with randomized caps and small letters.
â Mayank Porwal
8 hours ago
3
Possible duplicate of How do I modify a single character in a string, in Python?
â Sneftel
2 hours ago
add a comment |Â
Use another container, like alist
, then create the string from that. Alternatively, create a new sting incrementally
â juanpa.arrivillaga
8 hours ago
You can always create a new String with randomized caps and small letters.
â Mayank Porwal
8 hours ago
3
Possible duplicate of How do I modify a single character in a string, in Python?
â Sneftel
2 hours ago
Use another container, like a
list
, then create the string from that. Alternatively, create a new sting incrementallyâ juanpa.arrivillaga
8 hours ago
Use another container, like a
list
, then create the string from that. Alternatively, create a new sting incrementallyâ juanpa.arrivillaga
8 hours ago
You can always create a new String with randomized caps and small letters.
â Mayank Porwal
8 hours ago
You can always create a new String with randomized caps and small letters.
â Mayank Porwal
8 hours ago
3
3
Possible duplicate of How do I modify a single character in a string, in Python?
â Sneftel
2 hours ago
Possible duplicate of How do I modify a single character in a string, in Python?
â Sneftel
2 hours ago
add a comment |Â
7 Answers
7
active
oldest
votes
up vote
15
down vote
accepted
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
1
No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list tojoin
, resulting in more overhead in both time and memory. With a generator expression, thejoin
method would be able to simply iterate through the generator output as the generator produces item values one by one.
â blhsing
8 hours ago
1
Nice.., thanks for telling me
â U9-Forward
8 hours ago
6
@U9-Forward You are correct.join
needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.
â timgeb
8 hours ago
1
@timgeb Oh i am right, wow, now i know :-)
â U9-Forward
8 hours ago
2
@timgeb I stand corrected then. Thanks.
â blhsing
8 hours ago
 |Â
show 1 more comment
up vote
5
down vote
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.
add a comment |Â
up vote
3
down vote
Just change the string implementation to a list implementation. As string is immutable, you cannot change the value inside the object. But Lists
can be, So I've only changed that part of your code. And make note that there are much better ways to do this, Follow here
import random
sentence = "This is a test sentence" # Strings are immutable
i =0
new_sentence = # Lists are mutable sequences
for c in sentence:
case = random.randint(0,1)
print("case = ", case)
if case == 0:
print("here0")
new_sentence += sentence[i].lower() # append to the list
else:
print("here1")
new_sentence += sentence[i].upper() # append to the list
i += 1
print ("new sentence = ", new_sentence)
# to print as string
new_sent = ''.join(new_sentence)
print(new_sent)
add a comment |Â
up vote
2
down vote
sentence='quick test'
print(''.join([char.lower() if random.randint(0,1) else char.upper() for char in word ]))
qUiCK TEsT
1
you can pass your list to''join()
for a more complete solution
â Ev. Kounis
8 hours ago
add a comment |Â
up vote
1
down vote
You can do like below
char_list =
for c in sentence:
ucase = random.randint(0,1)
print("case = ", case)
if ucase:
print("here1")
char_list.append(c.upper())
else:
print("here0")
char_list.append(c.lower())
print ("new sentence = ", ''.join(char_list))
add a comment |Â
up vote
-1
down vote
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'
add a comment |Â
up vote
-2
down vote
Use random.choice
:
from random import choice
s = 'Hello World'
print(''.join([choice((i.upper(),i.lower())) for i in s]))
Output (random so no specific one):
hELLo worLD
add a comment |Â
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
15
down vote
accepted
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
1
No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list tojoin
, resulting in more overhead in both time and memory. With a generator expression, thejoin
method would be able to simply iterate through the generator output as the generator produces item values one by one.
â blhsing
8 hours ago
1
Nice.., thanks for telling me
â U9-Forward
8 hours ago
6
@U9-Forward You are correct.join
needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.
â timgeb
8 hours ago
1
@timgeb Oh i am right, wow, now i know :-)
â U9-Forward
8 hours ago
2
@timgeb I stand corrected then. Thanks.
â blhsing
8 hours ago
 |Â
show 1 more comment
up vote
15
down vote
accepted
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
1
No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list tojoin
, resulting in more overhead in both time and memory. With a generator expression, thejoin
method would be able to simply iterate through the generator output as the generator produces item values one by one.
â blhsing
8 hours ago
1
Nice.., thanks for telling me
â U9-Forward
8 hours ago
6
@U9-Forward You are correct.join
needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.
â timgeb
8 hours ago
1
@timgeb Oh i am right, wow, now i know :-)
â U9-Forward
8 hours ago
2
@timgeb I stand corrected then. Thanks.
â blhsing
8 hours ago
 |Â
show 1 more comment
up vote
15
down vote
accepted
up vote
15
down vote
accepted
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
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
answered 8 hours ago
blhsing
23.7k41134
23.7k41134
1
No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list tojoin
, resulting in more overhead in both time and memory. With a generator expression, thejoin
method would be able to simply iterate through the generator output as the generator produces item values one by one.
â blhsing
8 hours ago
1
Nice.., thanks for telling me
â U9-Forward
8 hours ago
6
@U9-Forward You are correct.join
needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.
â timgeb
8 hours ago
1
@timgeb Oh i am right, wow, now i know :-)
â U9-Forward
8 hours ago
2
@timgeb I stand corrected then. Thanks.
â blhsing
8 hours ago
 |Â
show 1 more comment
1
No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list tojoin
, resulting in more overhead in both time and memory. With a generator expression, thejoin
method would be able to simply iterate through the generator output as the generator produces item values one by one.
â blhsing
8 hours ago
1
Nice.., thanks for telling me
â U9-Forward
8 hours ago
6
@U9-Forward You are correct.join
needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.
â timgeb
8 hours ago
1
@timgeb Oh i am right, wow, now i know :-)
â U9-Forward
8 hours ago
2
@timgeb I stand corrected then. Thanks.
â blhsing
8 hours ago
1
1
No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list to
join
, resulting in more overhead in both time and memory. With a generator expression, the join
method would be able to simply iterate through the generator output as the generator produces item values one by one.â blhsing
8 hours ago
No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list to
join
, resulting in more overhead in both time and memory. With a generator expression, the join
method would be able to simply iterate through the generator output as the generator produces item values one by one.â blhsing
8 hours ago
1
1
Nice.., thanks for telling me
â U9-Forward
8 hours ago
Nice.., thanks for telling me
â U9-Forward
8 hours ago
6
6
@U9-Forward You are correct.
join
needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.â timgeb
8 hours ago
@U9-Forward You are correct.
join
needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.â timgeb
8 hours ago
1
1
@timgeb Oh i am right, wow, now i know :-)
â U9-Forward
8 hours ago
@timgeb Oh i am right, wow, now i know :-)
â U9-Forward
8 hours ago
2
2
@timgeb I stand corrected then. Thanks.
â blhsing
8 hours ago
@timgeb I stand corrected then. Thanks.
â blhsing
8 hours ago
 |Â
show 1 more comment
up vote
5
down vote
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.
add a comment |Â
up vote
5
down vote
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.
add a comment |Â
up vote
5
down vote
up vote
5
down vote
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.
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.
answered 8 hours ago
timgeb
39.4k105278
39.4k105278
add a comment |Â
add a comment |Â
up vote
3
down vote
Just change the string implementation to a list implementation. As string is immutable, you cannot change the value inside the object. But Lists
can be, So I've only changed that part of your code. And make note that there are much better ways to do this, Follow here
import random
sentence = "This is a test sentence" # Strings are immutable
i =0
new_sentence = # Lists are mutable sequences
for c in sentence:
case = random.randint(0,1)
print("case = ", case)
if case == 0:
print("here0")
new_sentence += sentence[i].lower() # append to the list
else:
print("here1")
new_sentence += sentence[i].upper() # append to the list
i += 1
print ("new sentence = ", new_sentence)
# to print as string
new_sent = ''.join(new_sentence)
print(new_sent)
add a comment |Â
up vote
3
down vote
Just change the string implementation to a list implementation. As string is immutable, you cannot change the value inside the object. But Lists
can be, So I've only changed that part of your code. And make note that there are much better ways to do this, Follow here
import random
sentence = "This is a test sentence" # Strings are immutable
i =0
new_sentence = # Lists are mutable sequences
for c in sentence:
case = random.randint(0,1)
print("case = ", case)
if case == 0:
print("here0")
new_sentence += sentence[i].lower() # append to the list
else:
print("here1")
new_sentence += sentence[i].upper() # append to the list
i += 1
print ("new sentence = ", new_sentence)
# to print as string
new_sent = ''.join(new_sentence)
print(new_sent)
add a comment |Â
up vote
3
down vote
up vote
3
down vote
Just change the string implementation to a list implementation. As string is immutable, you cannot change the value inside the object. But Lists
can be, So I've only changed that part of your code. And make note that there are much better ways to do this, Follow here
import random
sentence = "This is a test sentence" # Strings are immutable
i =0
new_sentence = # Lists are mutable sequences
for c in sentence:
case = random.randint(0,1)
print("case = ", case)
if case == 0:
print("here0")
new_sentence += sentence[i].lower() # append to the list
else:
print("here1")
new_sentence += sentence[i].upper() # append to the list
i += 1
print ("new sentence = ", new_sentence)
# to print as string
new_sent = ''.join(new_sentence)
print(new_sent)
Just change the string implementation to a list implementation. As string is immutable, you cannot change the value inside the object. But Lists
can be, So I've only changed that part of your code. And make note that there are much better ways to do this, Follow here
import random
sentence = "This is a test sentence" # Strings are immutable
i =0
new_sentence = # Lists are mutable sequences
for c in sentence:
case = random.randint(0,1)
print("case = ", case)
if case == 0:
print("here0")
new_sentence += sentence[i].lower() # append to the list
else:
print("here1")
new_sentence += sentence[i].upper() # append to the list
i += 1
print ("new sentence = ", new_sentence)
# to print as string
new_sent = ''.join(new_sentence)
print(new_sent)
edited 8 hours ago
answered 8 hours ago
Vineeth Sai
1,46211019
1,46211019
add a comment |Â
add a comment |Â
up vote
2
down vote
sentence='quick test'
print(''.join([char.lower() if random.randint(0,1) else char.upper() for char in word ]))
qUiCK TEsT
1
you can pass your list to''join()
for a more complete solution
â Ev. Kounis
8 hours ago
add a comment |Â
up vote
2
down vote
sentence='quick test'
print(''.join([char.lower() if random.randint(0,1) else char.upper() for char in word ]))
qUiCK TEsT
1
you can pass your list to''join()
for a more complete solution
â Ev. Kounis
8 hours ago
add a comment |Â
up vote
2
down vote
up vote
2
down vote
sentence='quick test'
print(''.join([char.lower() if random.randint(0,1) else char.upper() for char in word ]))
qUiCK TEsT
sentence='quick test'
print(''.join([char.lower() if random.randint(0,1) else char.upper() for char in word ]))
qUiCK TEsT
edited 8 hours ago
answered 8 hours ago
AILearning
149111
149111
1
you can pass your list to''join()
for a more complete solution
â Ev. Kounis
8 hours ago
add a comment |Â
1
you can pass your list to''join()
for a more complete solution
â Ev. Kounis
8 hours ago
1
1
you can pass your list to
''join()
for a more complete solutionâ Ev. Kounis
8 hours ago
you can pass your list to
''join()
for a more complete solutionâ Ev. Kounis
8 hours ago
add a comment |Â
up vote
1
down vote
You can do like below
char_list =
for c in sentence:
ucase = random.randint(0,1)
print("case = ", case)
if ucase:
print("here1")
char_list.append(c.upper())
else:
print("here0")
char_list.append(c.lower())
print ("new sentence = ", ''.join(char_list))
add a comment |Â
up vote
1
down vote
You can do like below
char_list =
for c in sentence:
ucase = random.randint(0,1)
print("case = ", case)
if ucase:
print("here1")
char_list.append(c.upper())
else:
print("here0")
char_list.append(c.lower())
print ("new sentence = ", ''.join(char_list))
add a comment |Â
up vote
1
down vote
up vote
1
down vote
You can do like below
char_list =
for c in sentence:
ucase = random.randint(0,1)
print("case = ", case)
if ucase:
print("here1")
char_list.append(c.upper())
else:
print("here0")
char_list.append(c.lower())
print ("new sentence = ", ''.join(char_list))
You can do like below
char_list =
for c in sentence:
ucase = random.randint(0,1)
print("case = ", case)
if ucase:
print("here1")
char_list.append(c.upper())
else:
print("here0")
char_list.append(c.lower())
print ("new sentence = ", ''.join(char_list))
answered 8 hours ago
ansu5555
1816
1816
add a comment |Â
add a comment |Â
up vote
-1
down vote
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'
add a comment |Â
up vote
-1
down vote
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'
add a comment |Â
up vote
-1
down vote
up vote
-1
down vote
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'
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'
answered 8 hours ago
ZisIsNotZis
99211
99211
add a comment |Â
add a comment |Â
up vote
-2
down vote
Use random.choice
:
from random import choice
s = 'Hello World'
print(''.join([choice((i.upper(),i.lower())) for i in s]))
Output (random so no specific one):
hELLo worLD
add a comment |Â
up vote
-2
down vote
Use random.choice
:
from random import choice
s = 'Hello World'
print(''.join([choice((i.upper(),i.lower())) for i in s]))
Output (random so no specific one):
hELLo worLD
add a comment |Â
up vote
-2
down vote
up vote
-2
down vote
Use random.choice
:
from random import choice
s = 'Hello World'
print(''.join([choice((i.upper(),i.lower())) for i in s]))
Output (random so no specific one):
hELLo worLD
Use random.choice
:
from random import choice
s = 'Hello World'
print(''.join([choice((i.upper(),i.lower())) for i in s]))
Output (random so no specific one):
hELLo worLD
edited 8 hours ago
answered 8 hours ago
U9-Forward
7,5272730
7,5272730
add a comment |Â
add a comment |Â
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52942497%2frandomly-capitalize-letters-in-string%23new-answer', 'question_page');
);
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Use another container, like a
list
, then create the string from that. Alternatively, create a new sting incrementallyâ juanpa.arrivillaga
8 hours ago
You can always create a new String with randomized caps and small letters.
â Mayank Porwal
8 hours ago
3
Possible duplicate of How do I modify a single character in a string, in Python?
â Sneftel
2 hours ago