0
def stringi(file):
    doc = open(file, 'r')
    cont = doc.read()
    nums = []
    word = ""
    for i in cont:
        if i != " ":
            word += i
        else:
            nums.append(word)
            word = ""
    nums.append(word)
    doc.close()
    return nums

This prints >>> ['This', 'is', 'ship', 'line', '132', '43', 'hello\n'] from a file which has: "This is ship line 132 43 hello"

How do I remove the \n part or at least a specific character in an element? (I'm aware that there are modules to do what I want with making each word an element but I'm a beginner and want to learn other ways.)

khelwood
  • 55,782
  • 14
  • 81
  • 108

1 Answers1

0

\n

represent here a new line character which can simply be ignored by using:

.strip()

Beside that, you can use

str.replace('\n', "")

  • Hi, thanks. Also how would i be able to remove a specific character in one of the elements by its location i.e string[1][2] – George kirby Jun 08 '21 at 13:26
  • Check out the **re** package of python. You can remove all the unnecessary characters by defining the rest of the pattern will be taken care of by the "re". If you're trying to replace something in a list you can simply apply list comprehension i.e `[num.replace('\n','') for num in nums]` – Adnan Khan Jun 09 '21 at 06:53