Muffen
Muffen

Reputation: 57

Converting specific letters to uppercase or lowercase in python

So to return a copy of a string converted to lowercase or uppercase one obviously uses the lower() or upper().

But how does one go about making a copy of a string with specific letters converted to upper or lowercase. For example how would i convert 'test' into 'TesT'

this is honestly baffling me so help is greatly appreciated

got it, thanks for the help Cyber and Matt!

Upvotes: 4

Views: 37467

Answers (9)

Jože Ws
Jože Ws

Reputation: 1814

Simply

chars_to_lower = "MTW"
"".join([char.lower() if char in chars_to_lower else char for char in item]

Upvotes: 0

Plo_Koon
Plo_Koon

Reputation: 3033

The simplest solution:

>>> letters = "abcdefghijklmnop"
>>> trantab = str.maketrans(letters, letters.upper())
>>> print("test string".translate(trantab))
tEst strING

Upvotes: 0

Anjali Shyamsundar
Anjali Shyamsundar

Reputation: 555

Python3 can do:

def myfunc(str):
  if len(str)>3:
    return str[:3].capitalize() + str[3:].capitalize()
  else:
    return 'Word is too short!!'

Upvotes: 0

Niicodemus
Niicodemus

Reputation: 327

I would use translate().

For python2:

>>> from string import maketrans
>>> "test".translate(maketrans("bfty", "BFTY"))
'TesT'

And for python3:

>>> "test".translate(str.maketrans("bfty", "BFTY"))
'TesT'

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168586

You could use the str.translate() method:

import string

# Letters that should be upper-cased
letters = "tzqryp"
table = string.maketrans(letters, letters.upper())


word = "test"
print word.translate(table)

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117856

As a general way to replace all of a letter with something else

>>> swaps = {'t':'T', 'd':'D'}
>>> ''.join(swaps.get(i,i) for i in 'dictionary')
'DicTionary'

Upvotes: 0

MattDMo
MattDMo

Reputation: 102842

If you're just looking to replace specific letters:

>>> s = "test"
>>> s.replace("t", "T")
'TesT'

Upvotes: 5

RNikoopour
RNikoopour

Reputation: 533

import re
input = 'test'
change_to_upper = 't'
input = re.sub(change_to_upper, change_to_upper.upper(), input)

This uses the regular expression engine to say find anything that matches change_to_upper and replace it with the the upper case version.

Upvotes: 1

Daniel
Daniel

Reputation: 42748

There is one obvious solution, slice the string and upper the parts you want:

test = 'test'
test = test[0].upper() + test[1:-1] + test[-1].upper()

Upvotes: 4

Related Questions