[Tutor] Please take a look at this function
Richard D. Moores
rdmoores at gmail.com
Fri Dec 18 01:57:57 CET 2009
def prestrings2list(a_str):
word = ""
list_of_strings = []
length_of_a_string = len(a_str)
for i, char in enumerate(a_str):
if i == length_of_a_string - 1:
word += char
word = word.rstrip()
list_of_strings.append(word)
elif char == ",":
word = word.strip()
list_of_strings.append(word)
word = ""
elif char != " ":
word += char
elif char == " " and word != "" and a_str[i - 1] != " ":
word += char
return list_of_strings
The idea for this came from looking at the interests of bloggers on a
blogging site. Some have a great many interests listed -- so many that I
thought it would handy to have a function that could put them in a Python
list so they could be counted, sorted, dupes weeded out, etc.
For example, here's a shorter one that I copied and pasted, modified, and
then pasted again into a pair of quotes, thereby creating one long Python
string:
a_str = "blender , synthetic DNA, myrmecology, fungi, quorum sensing,
theoretical physic's, reason, love, hope, virtual reality, google operating
system, space, life, mystery, truth's, universe, immortality, strangeness,
fun ,living, hope, eternity, knowledge, Egyptian secrets of the dead,
n-space, hyper-time , theory of everything, light, nuclear theory, particle
theory, myrmec, self replicating RNA, MMOG, MMOR%PG, symbiosis,Black's
Plague, selddir, Da Vinci, Newton, Archimedes, Cantor7,
Leibnitz,myrmecology"
prestrings2list(a_str) returns
['blender', 'synthetic DNA', 'myrmecology', 'fungi', 'quorum sensing',
"theoretical physic's", 'reason', 'love', 'hope', 'virtual reality', 'google
operating system', 'space', 'life', 'mystery', "truth's", 'universe',
'immortality', 'strangeness', 'fun', 'living', 'hope', 'eternity',
'knowledge', 'Egyptian secrets of the dead', 'n-space', 'hyper-time',
'theory of everything', 'light', 'nuclear theory', 'particle theory',
'myrmec', 'self replicating RNA', 'MMOG', 'MMOR%PG', 'symbiosis', "Black's
Plague", 'selddir', 'Da Vinci', 'Newton', 'Archimedes', 'Cantor7',
'Leibnitz', 'myrmecology']
This is exactly what I wanted, but please tell me if the function name makes
any sense, and if the function could be made to conform better to standard
Python practice. And what a good docstring for it might be.
I've assumed that the items in these strings will be separated by commas.
But there could be some using semicolons instead. That revision will be easy
to make.
Thanks, Tutors,
Dick Moores
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091217/a5cdf7bd/attachment-0001.htm>
More information about the Tutor
mailing list