Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – naming parameters from enumerate

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading