I want to divide strings or integers to operate with their components and then print out a string. Should I create a list (to be printed as a string) or another string to include all the components before printing? What are the differences of the two methods?
While we can treat a string as a interable, I've seen it suggested that we treat them as immutable objects. Here is proof that a string is iterable:
x = iter("this is a string") while True: try: print x.next(), except StopIteration: print print "Bye" break
Output in console:
t h i s i s a s t r i n g Bye
Rexpecting immutability, we could generate a list, then iterate the list to construct a new list, which is then joined at conclusion to form a new string. I'm o expert so cannot go into any further detail.
There are weaknesses in the above that I can already spot. For instance, what need have we of a list if
x is already and iterator? If we are only mining data from a string, then iterating the string is wholly appropriate. No changes are being made to the string. In other words, use a string iterator.
x = "this is a string" y = [ k for k in x ] print y
The yield is another iterable, a list, and we have not modified the string.
['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g']
But if our objective was to convert the string to a list there are better ways. What we have here is a means to create a special list, filtered and/or modified to suit. ROT13 comes to mind, or a weird upper case function...
z = [ chr(ord(k)%32+64) for k in x ] print z
['T', 'H', 'I', 'S', '@', 'I', 'S', '@', 'A', '@', 'S', 'T', 'R', 'I', 'N', 'G']
We can make a correction for the @ character by skipping over spaces and not encoding them.
z = [ chr(ord(k)%32+64) if k != ' ' else ' ' for k in x ] print z
['T', 'H', 'I', 'S', ' ', 'I', 'S', ' ', 'A', ' ', 'S', 'T', 'R', 'I', 'N', 'G']
It really comes down to what you need your iterator to do. String, list, dictinoary, they all have a role to play. What are the dictates, and what are the objectives? Each opens their own can of worms.