3

I have this name list that i got online,the list is 200 names long,here is a sample of it that i have saved in a text file.

John
Noah
William
James
Logan
Benjamin
...

I want them to be a list of strings i.e

x=['John','Noah','William',...]

I searched for questions similar but didn't find exactly what i need, any help is much appreciated.

2
  • 3
    what is the input ? one string ? Commented Nov 20, 2018 at 2:01
  • @W-B yes it a text of names,just as in the question Commented Nov 20, 2018 at 2:07

3 Answers 3

2

If the input is a file you can do...

x = []
with open('file_name', 'r') as f:
    for line in f:
       x.append(line.strip())
Sign up to request clarification or add additional context in comments.

Comments

1

Additionally to The Pineapple's answer, you can also do list comprehension:

with open('file_name', 'r') as f:
    x=[i.rstrip() for i in f]

Now:

print(x)

Is the 200 names in a list.

4 Comments

it is a text seperated by '\n' inside a notepad(each name is on a line)
This does not make sense. How can you iterate over f ?
@mad_ Of course you can!, Demo of an answer of that: stackoverflow.com/questions/3277503/…
@U9-Forward i wish i knew how to accept an answer,i am not seeing the button :)
0

If data is contained in a file

with open('file_name', 'r') as f:
    data=f.readlines() # this will be a list of names

OR

with open('file_name', 'r') as f:
        data=f.read().splitlines() # to remove the trailing '\n'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.