How can I convert a specific letter in a string, i.e all the the a
s in 'ahdhkhkahfkahafafkh'
to uppercase?
I can only seem to find ways to capitalize the first word or upper/lower case the entire string.
How can I convert a specific letter in a string, i.e all the the a
s in 'ahdhkhkahfkahafafkh'
to uppercase?
I can only seem to find ways to capitalize the first word or upper/lower case the entire string.
You can use str.translate
with string.maketrans
:
>>> import string
>>> table = string.maketrans('a', 'A')
>>> 'abcdefgahajkl'.translate(table)
'AbcdefgAhAjkl'
This really shines if you want to replace 'a'
and 'b'
with their uppercase versions... then you just change the translation table:
table = string.maketrans('ab', 'AB')
Or, you can use str.replace
if you really are only doing a 1 for 1 swap:
>>> 'abcdefgahajkl'.replace('a', 'A')
'AbcdefgAhAjkl'
This method shines when you only have one replacement. It replaces substrings rather than characters, so 'Bat'.replace('Ba', 'Cas')
-> 'Cast'
.
'banana'.replace('a', "A")
From the docs: https://docs.python.org/2/library/string.html#string.replace
>>> a = 'ahdhkhkahfkahafafkh'
>>> "".join(i.upper() if i == 'a' else i for i in a)
'AhdhkhkAhfkAhAfAfkh'
Or
>>> a.replace('a',"A")
'AhdhkhkAhfkAhAfAfkh'