1

I have been looking for an answer to this for a while but keep finding answers about stripping a specific string from a list.

Let's say this is my list of strings

stringList = ["cat\n","dog\n","bird\n","rat\n","snake\n"]

But all list items contain a new line character (\n)

How can I remove this from all the strings within the list?

sahasrara62
  • 10,069
  • 3
  • 29
  • 44
jessyjack
  • 35
  • 4
  • 1
    Iterate over the list, call `.strip()` on each word, and assign the result back to the list. What is the difficulty? – John Gordon May 14 '22 at 12:35
  • Does this answer your question? [How do I remove a trailing newline?](https://stackoverflow.com/questions/275018/how-do-i-remove-a-trailing-newline) – sahasrara62 May 14 '22 at 12:38

4 Answers4

1

Use a list comprehension with rstrip():

stringList = ["cat\n","dog\n","bird\n","rat\n","snake\n"]
output = [x.rstrip() for x in stringList]
print(output)  # ['cat', 'dog', 'bird', 'rat', 'snake']

If you really want to target a single newline character only at the end of each string, then we can get more precise with re.sub:

stringList = ["cat\n","dog\n","bird\n","rat\n","snake\n"]
output = [re.sub(r'\n$', '', x) for x in stringList]
print(output)  # ['cat', 'dog', 'bird', 'rat', 'snake']
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

You could also use map() along with str.rstrip:

>>> string_list = ['cat\n', 'dog\n', 'bird\n', 'rat\n', 'snake\n']
>>> new_string_list = list(map(str.rstrip, string_list))
>>> new_string_list
['cat', 'dog', 'bird', 'rat', 'snake']
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1

By applying the method strip (or rstrip) to all terms of the list with map

out = list(map(str.strip, stringList))
print(out)

or with a more rudimental check and slice

strip_char = '\n'
out = [s[:-len(strip_char)] if s.endswith(strip_char) else s for s in stringList]
print(out)
cards
  • 3,936
  • 1
  • 7
  • 25
1

Since you can use an if to check if a new line character exists in a string, you can use the code below to detect string elements with the new line character and replace those characters with empty strings

stringList = ["cat\n","dog\n","bird\n","rat\n","snake\n"]
nlist = []
for string in stringList:
    if "\n" in string:
        nlist.append(string.replace("\n" , ""))
print(nlist)
TechGeek
  • 316
  • 1
  • 11