1

I am trying to write a program as a python beginner. This function scans the given text. Whenever I come across the symbols “@, &, % or $”, I have to take the text until that point and print it as a single line. Also, I have to skip the symbol, start the next line from the letter right after the symbol and print it until I come across another symbol. I hope I told it well.

symbols= "@, &, %, $”"
for symbol in text:
     if text.startswith (symbols):
        print (text)

I know it's not correct but that was all I could think. Any help is appreciated.

Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
  • Does this answer your question? [split string on a number of different characters](https://stackoverflow.com/questions/373459/split-string-on-a-number-of-different-characters) – Joe Dec 26 '20 at 11:03

2 Answers2

1

IIUC, you need to split the string by each of the delimiters, so you could do the following:

symbols = "@, &, %, $".split(', ')
print(symbols)  # this is a list

text = "The first @ The second & and here you have % and finally $"

# make a copy of text
replaced = text[:]

# unify delimiters
for symbol in symbols:
    replaced = replaced.replace(symbol, '@')

print(replaced)  # now the string only have @ in the place of other symbols

for chunk in replaced.split('@'):
    if chunk:  # avoid printing empty strings
        print(chunk)

Output

['@', '&', '%', '$']  # print(symbols)
The first @ The second @ and here you have @ and finally @  # print(replaced)
The first 
 The second 
 and here you have 
 and finally 

The first step:

symbols = "@, &, %, $".split(', ')
print(symbols)  # this is a list

converts your string to a list. The second step replaces, using replace, all symbols with only one because str.split only works with a single string:

# unify delimiters
for symbol in symbols:
    replaced = replaced.replace(symbol, '@') 

The third and final step is to split the string by the chosen symbol (i.e @):

for chunk in replaced.split('@'):
    if chunk:  # avoid printing empty strings
        print(chunk)
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • 1
    Thank you! This is what I was trying to do. Have a nice day :)) @DaniMesejo –  Nov 29 '20 at 12:08
0

If I follow the instructions given to you literally, I believe it translates into nothing fancier than just replacing each of those 4 special characters in the text by a newline character:

text = """This is a line with @ and & in it.
This line has % and $ in it.
This line has nothing intersting in it.
This line has just @ in it.
The end.
"""
text = text.replace('@', '\n').replace('&', '\n').replace('%', '\n').replace('$', '\n')
print(text)

Prints:

This is a line with 
 and 
 in it.
This line has 
 and 
 in it.
This line has nothing intersting in it.
This line has just 
 in it.
Booboo
  • 38,656
  • 3
  • 37
  • 60