Python – naming parameters from enumerate

Advertisements

Question:

Take the following:

def a(the_enumerate: enumerate):
   print("index: " + str(the_enumerate[0]), character: " + the_enumerate[1])

map(a, enumerate("test"))

Is there a way of naming the index and the current element (character) in a better way than:

index: int = the_enumerate[0]
character: int = the_enumerate[1]

Perhaps it would be something like this:

def a(the_enumerate: enumerate(index: int, character: str)):
   print("index: " + str(the_enumerate[0]), character: " + the_enumerate[1])

map(a, enumerate("test"))

Context:

My method feels like it could be written in a "nicer" way and i’m just going through a journey of what can be done:

# Version 1
def convert_pascal_casing_to_real_sentence(string_to_convert: str) -> str:
    def casing_check(the_enumerate: enumerate):
        result: str = ""

        if the_enumerate[0] != 0:
            result = " " +  the_enumerate[1].lower() if the_enumerate[1].isupper() else the_enumerate[1]
        else: 
            result = the_enumerate[1]
            
        return result

    return "".join(map(casing_check, enumerate(string_to_convert)))

# Version 2
def convert_pascal_casing_to_real_sentence(string_to_convert: str) -> str:
    output: str = ""

    for index, character in enumerate(string_to_convert):
        if index != 0:
            output += " " + character.lower() if character.isupper() else character
        else: 
            output += character

    return output

# Calling one of the two methods
print(convert_pascal_casing_to_real_sentence("HelloWorld"))

>Solution :

You can unpack the enumerate values as follow:

def a(the_enumerate: enumerate):
    index, char = the_enumerate
    print(f"index: {index} character: {char}")

giving you:

index: 0 character: t
index: 1 character: e
index: 2 character: s
index: 3 character: t

Leave a ReplyCancel reply