Nov-12-2023, 04:42 PM
More like this.
sentence = "All work and no play makes Jack a dull boy." print(f"The original sentence is: '{sentence}'\n") string_length = len(sentence) print(f"Length of string is: {string_length}") words = sentence.split() word_dict = {f"var_{i}": word for i, word in enumerate(words)} num_words = len(words) print(f"The number of words in the sentence is: {num_words}") # Use word_dict print(word_dict["var_0"]) print(word_dict["var_5"]) if "var_10" in word_dict: print(word_dict["var_10"]) else: print("The sentence does not have a eleventh word.")
Output:Length of string is: 43
The number of words in the sentence is: 10
All
makes
The sentence does not have a eleventh word.
So as suggests before in post,i make dictionary and do not mess with dynamically variables hidden in globals() dictionary.>>> word_dict {'var_0': 'All', 'var_1': 'work', 'var_2': 'and', 'var_3': 'no', 'var_4': 'play', 'var_5': 'makes', 'var_6': 'Jack', 'var_7': 'a', 'var_8': 'dull', 'var_9': 'boy.'} >>> word_dict['var_3'] 'no' >>> word_dict.get('var_8') 'dull' >>> word_dict.get('var_11', 'Value not in word_dict') 'Value not in word_dict'