Posts: 23 Threads: 11 Joined: Nov 2023 Good morning, I'm trying to create a number of variables that is dynamic. Lets say I have a string sentence = "All work and no play makes Jack a dull boy." and I count the number of words in the string using a counting scheme of some sort and arrive at a value of 10. I then want to create 10 variables and store each separate word into a different variable. I think I could use a function like this: while i < num_vars: var_name = ??? - I think I could just loop through numbers and concatenate for a name. Ie.. "var_" concatenated with i , then iterate i var_value = ??? - Should I use some string split function in python, or assign to an array and use array functions? exec(var_name + " = " + var_value) Thanks again for the help and I hope this makes sense. Posts: 1,835 Threads: 2 Joined: Apr 2017 Don't try to dynamically create variables, because that will lead to code that's difficult to maintain. Instead, use a list if you want to keep items in order, or use a dictionary if you want to associate names with the values. Posts: 23 Threads: 11 Joined: Nov 2023 Nov-12-2023, 03:46 PM (This post was last modified: Nov-12-2023, 03:52 PM by RockBlok.) I'm just working through one of the tutorial exercises, not sure if it ever makes sense to store in variables for later reuse (days or weeks later), but I'm fairly new at this. This code seems to do what I was looking for though. sentence = "All work and no play makes Jack a dull boy." print("The original sentence is: '", sentence, "'") print("") string_length = len(sentence) print("length of string is: ", string_length) delimeter = " " string_array = [string_length] string_array = sentence #if empty string set modifier to 0 if string_length == 0: count_modifier = 0 else: count_modifier = 1 num_vars = string_array.count(delimeter,0)+count_modifier print("The number of words in the sentence is: ", num_vars) i = 0 var_assignment_string = "" #Builds a string for assigning variable data from a list while i < num_vars: var_name = "var_" + str(i) var_assignment_string = var_assignment_string + var_name + "," i = i + 1 var_exec_string = var_assignment_string + " = sentence.split(' ')" exec(var_exec_string) print(var_0) print(var_5) print(var_9) Posts: 8,197 Threads: 162 Joined: Sep 2016 Nov-12-2023, 03:59 PM (This post was last modified: Nov-12-2023, 04:03 PM by buran.) Please, don't do this. Use proper data structure like list or dict. By the way, there are plenty of odd things in this code you show By the way, you can use indexes directly on the string, no need of lists, or dynamically created variables sentence = "All work and no play makes Jack a dull boy." delimiter = ' ' words = sentence.split(delimiter) print(f'First word is: {words[0]}') print(f'Sixth word is: {words[5]}')Output: First word is: All Sixth word is: makes Posts: 23 Threads: 11 Joined: Nov 2023 Hopefully I get better at this haha. I think the next chapter in the book gets into that, I'll try to avoid being odd in the future Posts: 7,398 Threads: 123 Joined: Sep 2016 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' Posts: 6,920 Threads: 22 Joined: Feb 2020 Maybe this is the step in the lesson plan where you learn that having dynamic variables is required for some tasks. In lesson 2 you learn that Python already has a dynamic variable that does exactly what you want, and it is called a list. ndc85430 and RockBlok like this post Posts: 1,210 Threads: 146 Joined: Jul 2017 Nov-13-2023, 12:06 PM (This post was last modified: Nov-13-2023, 12:06 PM by Pedroski55.) What happens if a word repeats? What about punctuation? Lose the punctuation? I think there are already modules for doing this kind of thing. from collections import Counter sentence = "All work and no play makes Jack a dull boy. Jack is a dull boy. Work makes him dull." words = sentence.split() wordCount = Counter(words) Output: Counter({'Jack': 2, 'a': 2, 'dull': 2, 'boy.': 2, 'All': 1, 'work': 1, 'and': 1, 'no': 1, 'play': 1, 'makes': 1, 'is': 1})
type(wordCount) Output: <class 'collections.Counter'>
wordCount['Jack'] Output: 2 Posts: 1,953 Threads: 8 Joined: Jun 2018 I concur that dictionary or list is the way to go. One way to create dictionary from sentence can be dictionary comprehension: >>> sentence = "All work and no play makes Jack a dull boy." >>> {f"var_{i}": v for i, v in enumerate(sentence.split())} {'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.'} >>> I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame. |