-3

How can I convert a specific letter in a string, i.e all the the as in 'ahdhkhkahfkahafafkh' to uppercase?

I can only seem to find ways to capitalize the first word or upper/lower case the entire string.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Finlandia_C
  • 385
  • 6
  • 19

3 Answers3

7

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'.

mgilson
  • 300,191
  • 65
  • 633
  • 696
2
'banana'.replace('a', "A")

From the docs: https://docs.python.org/2/library/string.html#string.replace

thumbtackthief
  • 6,093
  • 10
  • 41
  • 87
1
>>> a = 'ahdhkhkahfkahafafkh'
>>> "".join(i.upper() if i == 'a' else i for i in a)
'AhdhkhkAhfkAhAfAfkh'

Or

>>> a.replace('a',"A")
'AhdhkhkAhfkAhAfAfkh'
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140