Reputation: 33
I don't know if my title is correct or it makes sense but that's the only thing that I think of since the split() method turns/splits string inputs into list.
This is my code
import re
fruits = "apple,orange,mango*banana"
listOfFruits = re.split("[,*]",fruits)
storage = ""
for i in range(0, len(listOfFruits)):
storage = storage + ("({}) \n({})\n".format(listOfFruits[i], listOfFruits[i]))
finalStorage = storage + "\n"
print(finalStorage)
And the output looks like this
(apple)
(apple)
(orange)
(orange)
(mango)
(mango)
(banana)
(banana)
What I want is that whenever the code sees an asterisk(*), it will automatically indent itself inside of what words was before it
What I would like my output
(apple)
(apple)
(orange)
(orange)
(mango)
(banana)
(banana)
(mango)
Other example
fruits = "mango+banana+grapes,orange+apple
The expected output should look like this
(mango)
(banana)
(grapes)
(grapes)
(banana)
(mango)
(orange)
(apple)
(apple)
(orange)
Upvotes: 2
Views: 55
Reputation: 4219
You could use a recursive method to do the hard work, something like this:
def get_levels(section, tab_num=0):
if not section:
return ''
sublevels = get_levels(section[1:], tab_num + 1)
return '\t'*tab_num + '(' + section[0] + ')\n' + \
sublevels + ( '\n' if sublevels else '') + \
'\t'*tab_num + '(' + section[0] + ')'
def print_fruits(fruits):
listOfFruits = fruits.split(',')
storage = ""
for fruit in listOfFruits:
storage += get_levels(fruit.split('*'), 0) + '\n'
print(storage)
After calling print_fruits
with your sample the output is the following:
>>> print_fruits("apple,orange,mango*banana")
>>> print_fruits("mango*banana*grapes,orange*apple")
(apple)
(apple)
(orange)
(orange)
(mango)
(banana)
(banana)
(mango)
(mango)
(banana)
(grapes)
(grapes)
(banana)
(mango)
(orange)
(apple)
(apple)
(orange)
Upvotes: 1
Reputation: 16147
I would split on ,
and then when iterating over the results, treat any item with *
differently by using an if
statement.
If the item has a *
, split on the *
and enumerate the results, multiplying the enumerator by \t
to get the spacing right, then add the reverse of that to the end and join into a single string.
fruits = "mango*banana*grapes,orange*apple"
ListOfFruits = fruits.split(',')
storage = ""
for f in ListOfFruits:
if '*' not in f:
storage+= ("({}) \n({})\n".format(f,f))
else:
tab_fruits = f.split('*')
p = ['\t'*i + '('+x+')' +'\n' for i,x in enumerate(tab_fruits)]
p.extend(reversed(p))
storage+=''.join(p)
finalStorage = storage + "\n"
print(finalStorage)
Ouput
(mango)
(banana)
(grapes)
(grapes)
(banana)
(mango)
(orange)
(apple)
(apple)
(orange)
Upvotes: 1