pyperclip is a Python library for copying text to and pasting text from the system clipboard. Install it with pip before importing it. section 9.3.1
A typical clipboard workflow:
- Import pyperclip. section 9.3.1
- Call copy() to place text on the clipboard. section 9.3.1
- Call paste() to retrieve clipboard text into a variable. section 9.3.1
Cleaning email text
A cleanup function can paste email text, split it into lines, remove leading quotation marks and spaces, join the lines with newline characters, and copy the cleaned result back to the clipboard. section 9.3.2
```pythonimport pyperclip# Copy to clipboardpyperclip.copy('Hello, world!')# Paste from clipboardtext = pyperclip.paste()print(text)```
Shows the smallest complete example: copy a string, paste it into a variable, and print it. section 9.3.1
Listing 9.1 First try: Clean up email text in the clipboard
import pyperclip
def clean_email():
'''
The clipboard contains lines of text.
Clean up the text by removing any > or space
characters from the beginning of each line.
Replace the clipboard with the cleaned text.
'''
text = pyperclip.paste() #1
lines = text.splitlines() #2
for i in range(len(lines)): #3
lines[i] = lines[i].lstrip(' >') #4
text = ' #5
'.join(lines) #5
pyperclip.copy(text) #6
if __name__ == '__main__': #7
clean_email() #8
Shows a practical clipboard-processing function and its main sequence of operations. section 9.3.2
