0

s = "aB:cD"

def transform_string():

    string_Length = len(s)
    pos_colon = s.find(":")

    lowerCase = s.lower()
    upperCase = s.upper()

    string_partA = 0 + pos_colon

    res = lowerCase[:string_partA] + upperCase[string_partA:]

    return res

print(transform_string())
print()

The code is meant to have the part of the string before the colon lowercased and after the colon uppercased. So my question is what is

res = lowerCase[:string_partA] + upperCase[string_partA:]

the bracket in there is meant to be for, or more explicitly, when can we use that? Does that syntax have a name? I saw someone else use it and I could logically follow how it works and what it does, I just wonder if that has a name or syntax restrictions and so on...

I first tried to use a for loop (would appreciate if someone could tell me why that is wrong, I know it's not as efficient as the code above):

s = "aB:cD"

def transform_string():
    y = len(s)
    x = s.find(":")

    for s in range(0, x):
        first_half = s.lower()
    for s in range(x, y):
        second_half = s.upper()

    res = f"{first_half}+{second_half}"
    return res
print(transform_string())
print()

Thanks!

Jerry Cohen
  • 133
  • 5
  • 2
    `[]` is typically called a *subscript* operator. In the case of `lowerCase[:string_partA]` it's used together with list *slicing*. – Some programmer dude Sep 29 '22 at 09:41
  • 1
    This is the Concept of string `slicing` in Python You can find more about it here... https://www.pythoncentral.io/cutting-and-slicing-strings-in-python/ – Nikhil Sep 29 '22 at 09:42

1 Answers1

1

The reason you are wrong is that you want to (lower) or (upper) (an integer). When you put S in suffering, your S is equal to Integer The first time (S=0), the second time (S=1) and so on until the end But the above code finds out which section should be (lower) or (upper) by indexing Meanwhile, when you want to get (Lens) because (S) is defined outside the function, (Len) cannot be calculated. It is enough to write (global s) inside the function or give (s) as input to the function.

MK81
  • 24
  • 5