-1

I have a string that can either be written with caps lock or not. "With caps lock" means that it is either is like tHIS or like THIS. It is easy enough to detect the second case with "isupper()" function, but I wasn't able to find a way to find the first case reliably. For strings of length 1 I used "islower()" to detect if they should be capitalized, so it shouldn't be a problem

Code I used

import re
inp = input()
trutable = ""
for i in inp:
    if i.isupper():
        trutable += "1"
    if i.islower():
        trutable += "0"
pattern = re.compile(r'^01')
answ = re.match(pattern, trutable)
if inp.isupper() or answ != None or (len(inp) == 1 and inp.islower()):
    inp = inp.capitalize()

print(inp)
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Ive
  • 51
  • 1
  • 7
  • 2
    what is your question and purpose of this code, exactly?? – JayPeerachai Dec 13 '21 at 06:58
  • 1
    And your problem is? If you just want to capitalize any word - then do so. There is a huge group of words that belong into all-caps - like NBL, USA, CIA, FBI, etc. Adding to a string (`trutable`) btw is wasteful - it destroys the shorter one and creates a new one . It is better to use a list, append single characters and `string = ''.join(your_list)` them if needed - your `trutable` here is never used and distracts from a [mre]. – Patrick Artner Dec 13 '21 at 07:08

3 Answers3

2

Would you please try:

s = "hELLO wORLD!"
print(s.swapcase())

Output:

Hello World!
tshiono
  • 21,248
  • 2
  • 14
  • 22
1

You can follow this approach:

s = "hdCdjdC"

print("".join([x.upper() if x.islower() else x.lower() for x in s]))

OUTPUT

HDcDJDc
nikeros
  • 3,302
  • 2
  • 10
  • 26
1

For text character replacement python string has the str.maketrans and str.translate methods:

from string import ascii_lowercase as ascii_up, ascii_uppercase as ascii_low

def reverseCase(text):
    m = str.maketrans(ascii_low + ascii_up, ascii_up + ascii_low)
    return text.translate(m)


for w in ("tata", "TATA", "TaTa", "42"):
    print(reverseCase(w))

Output:

TATA
tata
tAtA
42

To detect things

[...] either is like 'tHIS' [...]

you can use:

def isWordStartingLowerAndContinuingUpperCased(word):
    """Check if words starts with lower case and continues upper cased."""
    return word[0].islower() and word[1:].isupper()

for w in ("tHIS", "This", "THIS"):
    print(w, ":", isWordStartingLowerAndContinuingUpperCased(w))

To get

tHIS : True 
This : False
THIS : False

When normalizing text be aware of false positives - there is a huge group of words that belong into all-caps and should not be changed - abbreviations:

NBL, USA, MIB, CIA, FBI, NSA, MI6, NASA, DARPA, etc.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Combination of your finding algorithm and replacing ```inp.capitalize()``` to ```inp.swapcase()``` made it so there were no issues! Thank you – Ive Dec 13 '21 at 10:31