1

I have an array that looks like this:

guest_list = ['P', 'r', 'o', 'f', '.', ' ', 'P', 'l', 'u', 'm', '\n', 'M', 'i', 's', 's', ' ', 'S', 'c', 'a', 'r', 'l', 'e', 't', '\n', 'C', 'o', 'l', '.', ' ', 'M', 'u', 's', 't', 'a', 'r', 'd', '\n', 'A', 'l', ' ', 'S', 'w', 'e', 'i', 'g', 'a', 'r', 't', '\n', 'R', 'o', 'b', 'o', 'c', 'o', 'p']

What I want is an array that looks like this:

guest_list = ['Prof.Plum', 'Miss Scarlet', 'Col. Mustard', 'Al Sweigart', 'Robocop']

In other words, until '\n' appears, I want all of the string values to be combined into 1 value.

Any suggestions?

Edit #1:

Here is part of my original code:

ogl = open('guests.txt') #open guest list
pyperclip.copy(ogl.read()) #open guest list copy
guest_list = list(pyperclip.paste())
11
  • 2
    It would be nice of you to put /some/ effort into your question. For example, your expected output is invalid. Also, in Python we call this "list" not "array". You should also show us what you have tried so far and how it has failed instead of expecting us to do your work for you. (And I'm even ignoring the fact that your input is very unlikely to occur unless you have some serious problems elsewhere in your code.) Commented May 16, 2018 at 23:53
  • I'm sorry. I am new to Python. I have like 1 month of experience using it :) Commented May 16, 2018 at 23:54
  • 5
    How did you get this list? It looks like there's some bad upstream processing that should be adjusted, like a list call on a string or a loop over individual characters. Commented May 16, 2018 at 23:55
  • 1
    Ah yea, calling list on a string creates an list of each character, call pyperclip.paste().split('\n') Commented May 17, 2018 at 0:04
  • 1
    Yes, that will work. I'm confused as to what the purpose of copying and pasting is here however, instead of just calling split('\n') on ogl.read() You could even use ogl.read().splitlines() Commented May 17, 2018 at 0:07

1 Answer 1

6

Simply use str.join and str.split:

>>> ''.join(x).split('\n')
['Prof. Plum', 'Miss Scarlet', 'Col. Mustard', 'Al Sweigart', 'Robocop']

Since you've updated your question to show how you read in the file, here is what you really should be doing:

with open('guests.txt') as ogl:
    pyperclip.copy(ogl.read())
    guest_list = pyperclip.paste().split('\n')

Or something along those lines, although I'm not sure why you are doing the copy/paste thing.

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

2 Comments

I am pasting into a word doc and I am very new to Python. I am importing a text and pasting into a word doc.
Ah, alright, I'm not familiar with the pyperclip library.

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.