Just as the title.
I want to store some strings inside the program, and later I may store them(the string) in a text file. And I do not want duplicating strings.

As I learned from school, I should use a hash table for it, but I may build a bad hash table. So, I would like to ask all of you, is there someway I can do it like I said in python?

Thanks.

If you do not have many strings, array of string should work. Normally you shouldn't worry about python efficency it has quite good code optimisation and python is not c it is not made for speed, so I would keep it simple and use something like array of strings.

but I want distinct strings.........and I don't want to loop it over to see if there is a existed string of the same.

but I want distinct strings.........and I don't want to loop it over to see if there is a existed string of the same.

You can use a set of strings

s = set(["hello", "world"])
s.add("anotherstring")
s.add("hello")
print s

or a dictionary (dict). Dict is the name of 'hash table' in python.

Just for the fun of Python ...

# using the Python local dictionary vars()
# you can dump/save and load mystr_dict with module pickle

def mystrings():
    s1 = 'I '
    s2 = 'like '
    s3 = 'Python'
    # in this case vars() is local to this function
    return vars()

mystr_dict = mystrings()

print(mystr_dict)  # {'s3': 'Python', 's2': 'like', 's1': 'I'}

# add mystr_dict to vars() local to __main__
vars = vars().update(mystr_dict)

print(s1+s2+s3)  # I like Python
commented: Nice, I never thought about returning vars() :) +3

Gribouillis makes some good suggestions.

As for storing the data to a file there are really two standard, commonplace options that I think are suited to this.

I'd either pickle or marshal the object.

pickle and marshal can store and retrieve a Python object on file.

Both are similar, but pickle creates a file that will work across platforms and marshal creates a file that will only work on a type of system it is created on.

I read another post you have, and if structured text is necessary I'd try to devise a solution using json, but I'm not familiar with it so I can't help you there.

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.