tadm123 tadm123 - 2 months ago 14
Python Question

(Python) Help in modfiying a string from the clipboard

Basically I'm copying a bunch of lists from https://en.wikipedia.org/wiki/List_of_lists_of_lists into my clipboard.
When I run my program, it will add bullets after and before each line.

For example:

Lists of Iranian films


Would convert into:

•• Lists of Iranian films ••


And so forth. The program works when I add bullets before the line but when I put them after it it just prints one long string without any newline characters. Can anyone tell me what am I doing wrong?

Here's the code:

#bulletPointAdder.py - Adds Wikipedia bullet points to the start and end
#of each line of text on the clipboard

import pyperclip
text=pyperclip.paste() #paste a big string of text from clipboard into the 'text' string


# Separate lines and add stars
lines = text.split('\n') #'lines' contains a list of all the individual lines up until '\n'
#lines= ['list of iserael films', 'list of italian films' ...]

for i in range(len(lines)): #loop through all indexes in the "lines" list
lines[i] = '••' + lines[i] + '••' #add bullets before and after each line

text = '\n'.join(lines) #put a '\n' in between the list members (joins them) into a single string
pyperclip.copy(text)


In my clipboard:

List of Israeli films before 1960
List of Israeli films of the 1960s
List of Israeli films of the 1970s
List of Israeli films of the 1980s


Clipboard pasted in Notepad:

••List of Israeli films before 1960••••List of Israeli films of the 1960s••••List of Israeli films of the 1970s••••List of Israeli films of the 1980s••

Answer

Make a small change to your code (use os.linesep instead of '\n'):

import os
import pyperclip
text=pyperclip.paste()     
                             #paste will paste a big string of text in 'text' string

# Separate lines and add stars
lines = text.split(os.linesep)     #lines contains a list of all the individual lines up cut before newline
                             #lines= ['list of iserael films', 'list of italian films' ...]

for i in range(len(lines)):         #loop through all indexes in the "lines" list
    lines[i] = '••' + lines[i] + '••'   #add bullets before and after each line

text = os.linesep.join(lines)         #put a newline in  between the list members (joins them) into a single string
pyperclip.copy(text)

Generally, a "new line" refers to any set of characters that is commonly interpreted as signaling a new line, which can include:

  • CR LF on DOS/Windows
  • CR on older Macs
  • LF on Unix variants, including modern Macs

CR is the Carriage Return ASCII character (Code 0x0D), usually represented as \r. LF is the Line Feed character (Code 0x0A), usually represented as \n.

Also, read this: https://blog.codinghorror.com/the-great-newline-schism/

I just wanted you to write an platform-agnostic solution. Hence os.linesep