Reputation: 57
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
Reputation: 1814
Simply
chars_to_lower = "MTW"
"".join([char.lower() if char in chars_to_lower else char for char in item]
Upvotes: 0
Reputation: 3033
The simplest solution:
>>> letters = "abcdefghijklmnop"
>>> trantab = str.maketrans(letters, letters.upper())
>>> print("test string".translate(trantab))
tEst strING
Upvotes: 0
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
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
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
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
Reputation: 102842
If you're just looking to replace specific letters:
>>> s = "test"
>>> s.replace("t", "T")
'TesT'
Upvotes: 5
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
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