Python Forum
Create X Number of Variables and Assign Data
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create X Number of Variables and Assign Data
#6
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'
RockBlok likes this post
Reply


Messages In This Thread
RE: Create X Number of Variables and Assign Data - by snippsat - Nov-12-2023, 04:42 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Better python library to create ER Diagram by using pandas data frames as tables klllmmm 0 1,389 Oct-19-2023, 01:01 PM
Last Post: klllmmm
Question How create programmatically variables ? SpongeB0B 6 1,657 Aug-19-2023, 05:10 AM
Last Post: SpongeB0B
  Delete strings from a list to create a new only number list Dvdscot 8 1,822 May-01-2023, 09:06 PM
Last Post: deanhystad
  Create simple live plot of stock data dram 2 3,062 Jan-27-2023, 04:34 AM
Last Post: CucumberNox
  Create a function for writing to SQL data to csv mg24 4 1,340 Oct-01-2022, 04:30 AM
Last Post: mg24
  Best way to accommodate unknown number of variables? Mark17 9 4,048 May-30-2022, 03:57 AM
Last Post: Skaperen
  Create array of values from 2 variables paulo79 1 1,202 Apr-19-2022, 08:28 PM
Last Post: deanhystad
  How to create 2 dimensional variables in Python? plumberpy 5 2,036 Mar-31-2022, 03:15 AM
Last Post: plumberpy
  Strategy on updating edits back to data table and object variables hammer 0 1,255 Dec-11-2021, 02:58 PM
Last Post: hammer
  How can I assign "multiple variables" to a single "value"? Psycpus 2 1,959 Oct-04-2021, 03:29 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020