Saturday, October 29, 2016

Python strings, list and tuples

Here is one that just removes parenthesis and their contents,uses all the capability.

text = "No parenth (alpha(how are you?) ((((add some)date),d) ending ) ) " # Sample
start = 0
end = start
size=len(text)
while start < size :
 print(text)
 end = text.find(')')
 if end < 0 : break
 start = text[0:end].rfind('(')
 if start < 0 : break
 text = text[0:start-1]+text[end+1:size-1]
 size=len(text)

Learning about python, still. C coders will first just write python like it is c code, hen slowly begin to thumb through the documentation.

Just playing around with the various python features, I modify the parenthesis remover. I capture the parenthesis in a list, along with the character pointer, and I can replace them later.

text = "No parenth (alpha(how are you?) ((((add some)date),d) ending ) )      "
mylist=[]
def parenthesis(text) :
 start = 0
 end = start
 size=len(text)
 while True :
  print(text)
  end = text.find(')')
  if end < 0 : break
  start = text[0:end].rfind('(')
  if start < 0 : break
  mylist.append((start+1,text[start+1:end]))
  text = text[0:start]+text[end+1:size]
  size=len(text)

parenthesis(text)
for i in range(len(mylist)) : print(mylist[i])


So, I have the strings methods, list methods,and tuples, I think, let me look it up...yes, I did a tuple!

One morer! I want to collect the parenthesies from outer first to inner:

def outer_first(text) :
 start = 0
 end = start
 size=len(text)
 while True :
  print(text)
  end = text.rfind(')')
  if end < 0 : break
  start = text[0:end].find('(')
  if start < 0 : break
  mylist.append((start+1,end-start,text[start+1:end]))
  text = text[start+1:end]
  size=len(text)


And I learn clear(), keeps the list, just empties it.

No comments: