Home > Software engineering >  how can I write code that searches for each \n newline character in a string and then adds a star j
how can I write code that searches for each \n newline character in a string and then adds a star j

Time:07-11

say I have a code like this- 'Lists of animals\nLists of aquarium life\nLists of biologists by author abbreviation\nLists of cultivars' and I want to write code that searches for each \n newline character in the string and then adds a star just after that how can I do that in PYTHON?

I don't want to use the split() method to return a list of strings, one for each line in the original string, and then add the star to the front of each string in the list.

the results should look like this:

  • Lists of animals
  • Lists of aquarium life
  • Lists of biologists by author abbreviation
  • Lists of cultivar

CodePudding user response:

Just loop through the string and find the \n character make that as a separator and print the output as per your expected output. below answer will helps your constraint I believe

string = "Lists of animals\nLists of aquarium life\nLists of biologists 
           by author abbreviation\nLists of cultivars"
j = 0
for i in range(len(string)):
    if string[i] == '\n':
        print("* "   string[j:i])
        j = i   1
print("* "   string[j:i]) 

Output of the above code is given below

* Lists of animals
* Lists of aquarium life
* Lists of biologists by author abbreviation
* Lists of cultivar

Here I just print the string as per your expected output, you can also save this in separate list if you want. For that you can append those print line in the separate list.

CodePudding user response:

EDIT: Why not just use str.replace?

string = "Lists of animals\nLists of aquarium life\nLists of biologists by author abbreviation\nLists of cultivars"
new = string.replace("\n", "\n* ")

OLD ANSWER (missed the part about adding asterisks)

You can loop through the string, although I don't understand why str.split is undesired:

string = "Lists of animals\nLists of aquarium life\nLists of biologists by author abbreviation\nLists of cultivars"
output = []
index = 0
while index < len(string) - 1:
    index  = 1
    if string[index] == "\n":
        output.append(string[:index])
        string = string[index   1:]
        index = 0
output.append(string)
  • Related