Home > other >  Python String adjust
Python String adjust

Time:02-06

Hello is use some method like .isupper() in a loop, or string[i 1] to find my lower char but i don't know how to do that

input in function -> "ThisIsMyChar"
expected -> "This is my char"

CodePudding user response:

I´ve done it with regex, could be done with less code but my intention is readable

import re

def split_by_upper(input_string):
    pattern = r'[A-Z][a-z]*'
    matches = re.findall(pattern, input_string)
    if (matches):
        output = matches[0]
        for word in matches[1:]:
            output  = ' '   word[0].lower()   word[1:]
        return output
    else:
        return input_string


print(split_by_upper("ThisIsMyChar"))
>> split_by_upper() -> "This is my char"

CodePudding user response:

You could use re.findall and str.lower:

>>> import re
>>> s = 'ThisIsMyChar'
>>> ' '.join(w.lower() if i >= 1 else w for i, w in enumerate(re.findall('.[^A-Z]*', s)))
'This is my char'

CodePudding user response:

You should first try by yourself. If you didn't get it done, you can do something like this:

# to parse input string
def parse(str):
  result= ""   str[0];
  for i in range(1, len(str)):
    ch = str[i]
    if ch.isupper():
      result  = " ";
    result  = ch.lower();
  return result;

# input string
str  = "ThisIsMyChar";
print(parse(str))

CodePudding user response:

First you need to run a for loop and check for Uppercase words then when you find it just add a space at the starting, lower the word and increment it to your new string. Simple, more code is explained in comments in the code itself.

def AddSpaceInTitleCaseString(string):
    NewStr = ""

    # Check for Uppercase string in the input string char-by-char.
    for i in string:
        # If it found one, add it to the NewStr variable with a space and lowering it's case.
        if i.isupper(): NewStr  = f" {i.lower()}"

        # Else just add it as usual.
        else: NewStr  = i

    # Before returning the NewStr, remove all the leading and trailing spaces from it.
    # And as shown in your question I'm assuming that you want the first letter or your new sentence,
    # to be in uppercase so just use 'capitalize' function for it.
    return NewStr.strip().capitalize()

# Test.
MyStr = AddSpaceInTitleCaseString("ThisIsMyChar")
print(MyStr)

# Output: "This is my char"

Hope it helped :)

CodePudding user response:

You can split it via Regex using r"(?=[A-Z])" pattern:

import re

txt = 'ThisIsMyChar'
c = re.compile(r"(?=[A-Z])")

first, *rest = [i.lower() for i in c.split(txt)][1:]
print(f'{first.title()} {" ".join(rest)}')

That [1:] at the end of list comprehension is because there is a split at the beginning of the text which gives you empty string as the first item in the list.

CodePudding user response:

Here is a concise regex solution:

import re

capital_letter_pattern = re.compile(r'(?!^)[A-Z]')

def add_spaces(string):
    return capital_letter_pattern.sub(lambda match: ' '   match[0].lower(), string)

if __name__ == '__main__':
    print(add_spaces('ThisIsMyChar'))

The pattern searches for capital letters ([A-Z]), and the (?!^) is negative lookahead that excludes the first character of the input ((?!foo) means "don't match foo, ^ is "start of line", so (?!^) is "don't match start of line").

The .sub(...) method of a pattern is usually used like pattern.sub('new text', 'my input string that I want changed'). You can also use a function in place of 'new text', in which case the function is called with the match object as an argument, and the value returned by the function is used as the replacement string.

The expression capital_letter_pattern.sub(lambda match: ' ' match[0].lower(), string) replaces all matches (all capital letters except at the start of the line) using a lambda function to add a space before and make the letter lowercase. match[0] means "the entirety of the matched text", which in this case is the captial letter.

  •  Tags:  
  • Related