Converting specific letters to uppercase or lowercase in python - 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!

If you're just looking to replace specific letters:
>>> s = "test"
>>> s.replace("t", "T")
'TesT'

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()

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.

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)

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'

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'

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

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

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

Related

Extracting a substring of a string in Python based on presence of another string

common is always present regardless of string. Using that information, I'd like to grab the substring that comes just before it, in this case, "banana":
string = "apple_orange_banana_common_fruit"
In this case, "fruit":
string = "fruit_common_apple_banana_orange"
How would I go about doing this in Python?
You can use re.search() to extract the substring:
>>> import re
>>> s = 'apple_orange_banana_common_fruit'
>>> re.search(r'([a-zA-Z]+)_common', s).group(1)
'banana'
This will return a list of matches:
import re
string = "apple_orange_banana_common_fruit"
preceding_word = re.findall("[A-Za-z]+(?=_common)", string)
If common only occurs once per string, you might be better off using hwnd's solution.
import re
string = "apple_orange_bananna_common_fruit"
preceding_word = re.search('([a-zAZ]+)(?=_common)', string)
print (preceding_word.group(1))
>>> string = "fruit_common_apple_banana_orange"
>>> parts = string.split('_')
>>> print parts[parts.index('common') - 1]
fruit
>>> string = "apple_orange_banana_common_fruit"
>>> parts = string.split('_')
>>> print parts[parts.index('common') - 1]
banana

Conversion of a specific character in a string to Upper Case

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

fast way to remove lowercase substrings from string?

What's an efficient way in Python (plain or using numpy) to remove all lowercase substring from a string s?
s = "FOObarFOOObBAR"
remove_lower(s) => "FOOFOOBAR"
Python3.x answer:
You can make a string translation table. Once that translation table has been created, you can use it repeatedly:
>>> import string
>>> table = str.maketrans('', '', string.ascii_lowercase)
>>> s = 'FOObarFOOObBAR'
>>> s.translate(table)
'FOOFOOOBAR'
When used this way, the first argument values map to the second argument values (where present). If absent, it is assumed to be an identity mapping. The third argument is the collection of values to be removed.
Old python2.x answer for anyone who cares:
I'd use str.translate. Only the delete step is performed if you pass None for the translation table. In this case, I pass the ascii_lowercase as the letters to be deleted.
>>> import string
>>> s = 'FOObarFOOObBAR'
>>> s.translate(None, string.ascii_lowercase)
'FOOFOOOBAR'
I doubt you'll find a faster way, but there's always timeit to compare different options if someone is motivated :).
My first approach would be ''.join(x for x in s if not x.islower())
If you need speed use mgilson answer, it is a lot faster.
>>> timeit.timeit("''.join(x for x in 'FOOBarBaz' if not x.islower())")
3.318969964981079
>>> timeit.timeit("'FOOBarBaz'.translate(None, string.ascii_lowercase)", "import string")
0.5369198322296143
>>> timeit.timeit("re.sub('[a-z]', '', 'FOOBarBaz')", "import re")
3.631659984588623
>>> timeit.timeit("r.sub('', 'FOOBarBaz')", "import re; r = re.compile('[a-z]')")
1.9642360210418701
>>> timeit.timeit("''.join(x for x in 'FOOBarBaz' if x not in lowercase)", "lowercase = set('abcdefghijklmnopqrstuvwxyz')")
2.9605889320373535
import re
remove_lower = lambda text: re.sub('[a-z]', '', text)
s = "FOObarFOOObBAR"
s = remove_lower(s)
print(s)
Try:
import re
s = "FOObarFOOObBAR"
remove_lower = re.sub(r'[^A-Z]',r'',s)
print(remove_lower)
output: FOOFOOOBAR

Python behavior of string in loop

In trying to capitalize a string at separators I encountered behavior I do not understand. Can someone please explain why the string s in reverted during the loop? Thanks.
s = 'these-three_words'
seperators = ('-','_')
for sep in seperators:
s = sep.join([i.capitalize() for i in s.split(sep)])
print s
print s
stdout:
These-Three_words
These-three_Words
These-three_Words
capitalize turns the first character uppercase and the rest of the string lowercase.
In the first iteration, it looks like this:
>>> [i.capitalize() for i in s.split('-')]
['These', 'Three_words']
In the second iteration, the strings are the separated into:
>>> [i for i in s.split('_')]
['These-Three', 'words']
So running capitalize on both will then turn the T in Three lowercase.
You could use title():
>>> s = 'these-three_words'
>>> print s.title()
These-Three_Words
str.capitalize capitalizes the first character and lowercases the remaining characters.
Capitalize() will return a copy of the string with only its first character capitalized. You could use this:
def cap(s):
return s[0].upper() + s[1:]

Capitalize a string

Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?
For example:
asimpletest -> Asimpletest
aSimpleTest -> ASimpleTest
I would like to be able to do all string lengths as well.
>>> b = "my name"
>>> b.capitalize()
'My name'
>>> b.title()
'My Name'
#saua is right, and
s = s[:1].upper() + s[1:]
will work for any string.
What about your_string.title()?
e.g. "banana".title() -> Banana
s = s[0].upper() + s[1:]
This should work with every string, except for the empty string (when s="").
this actually gives you a capitalized word, instead of just capitalizing the first letter
cApItAlIzE -> Capitalize
def capitalize(str):
return str[:1].upper() + str[1:].lower().......
for capitalize first word;
a="asimpletest"
print a.capitalize()
for make all the string uppercase use the following tip;
print a.upper()
this is the easy one i think.
You can use the str.capitalize() function to do that
In [1]: x = "hello"
In [2]: x.capitalize()
Out[2]: 'Hello'
Hope it helps.
Docs can be found here for string functions https://docs.python.org/2.6/library/string.html#string-functions
Below code capitializes first letter with space as a separtor
s="gf12 23sadasd"
print( string.capwords(s, ' ') )
Gf12 23sadasd
str = str[:].upper()
this is the easiest way to do it in my opinion

Categories

Resources