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)
4
  • 1
    PlainText = File1.read().rstrip() Commented Nov 5, 2021 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]. Commented Nov 5, 2021 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. Commented Nov 5, 2021 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. Commented Nov 5, 2021 at 19:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.