0

I am reading some text from a text file that says hello my name is Matthew. But when i print it it says ['Hello my name is matthew']. Does anyone know how to trim the [' '] from the string?

Code below

File1 = open('Text.txt')
PlainText = File1.readlines()
File1.close()
print(PlainText)
Tony
  • 9,672
  • 3
  • 47
  • 75
Matthew Doig
  • 25
  • 1
  • 4
  • 1
    `PlainText = File1.read().rstrip()` – OneCricketeer Nov 05 '21 at 19:33
  • 1
    When you print an object, python needs to decide what it should look like to humans. `['Hello my name is matthew']` is python's way of telling you that you have a list with a single string value. Your sring is at `PlainText[0]`. – tdelaney Nov 05 '21 at 19:36
  • You should use the method recommend by OneCricketeer. But the wrong way to do it would be simply `print(PlainText[0])`. Because the item is a list, so pulling out the first index in the list will get you your string. – Velocibadgery Nov 05 '21 at 19:36
  • There are different ways to read the file depending on what you want to do with it next. If your file only has a single line, then the `read` or `readline` methods are fine. If you want ot read multiple lines and have each line be a different string, then `readlines or `for line in File1:` would be the way to go. – tdelaney Nov 05 '21 at 19:39

1 Answers1

2

It’s because readlines returns a list.

If your file contained multiple lines you would have many elements in the list. But as you only have one line it is the only element in the list.

Check the IO documentation for other methods to read single lines.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Tony
  • 9,672
  • 3
  • 47
  • 75