Say I've written a function that will take an unlimited number of arguments and store them under different variables.
Since the use is able to input any number of strings, it's not possible to give names to all the variables that might be created.
So, how would I create variables when the program is running ? I would like to create variables that have progressive names like.. (for the example above), string_one, string_two, string_three.. or string1, string2 , string3

EDIT: Just did some googling... Could I use dictionaries?

Recommended Answers

All 2 Replies

IMHO, a dictionary would be the way to go ...

str_dict = {}
count = 1
while True:
    mystr = raw_input("Enter a string (just Enter to quit): ")
    if not mystr:
        break
    str_dict[count] = mystr
    count += 1

# test
print(str_dict)

# show string at key 2
key = 2
if key in str_dict:
    print(str_dict[2])

"""my output -->
Enter a string (just Enter to quit): aaaa
Enter a string (just Enter to quit): bbbb
Enter a string (just Enter to quit): cccc
Enter a string (just Enter to quit): 
{1: 'aaaa', 2: 'bbbb', 3: 'cccc'}
bbbb
"""

thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.