使用 pyperclip 将多行复制到 python 中的变量

Copy Multiple Lines to variable in python using pyperclip

我写的代码只是创建一个结构并打印成多行 如何创建一个包含所有行的字符串

import pyperclip
symbol = input('Symbol = ')
width = int(input('Width = '))
height = int(input('Height = '))

while height > 0:
 print(symbol * width)
 height = height - 1

print('\nCopy to Clipboard ?\nY For Yes\nN For No\n')
sel = input('')
if sel == 'Y':
 pyperclip.copy('Here i want to copy the Structure')
elif sel == 'N':
 print('Done')

您可以使用 f 字符串和加法。

results = ""
while height > 0:
    results += f"{symbol * width}\n"
    height - = 1

print(results)

这应该会产生与您编写代码相同的输出,但这次您有一个唯一的字符串。

您可以使用列表理解来构建字符串,然后一次性使用它们

import pyperclip
symbol = input('Symbol = ')
width = int(input('Width = '))
height = int(input('Height = '))

structure = '\n'.join([symbol * width for x in range(height)])

print('\nCopy to Clipboard ?\nY For Yes\nN For No\n')
sel = input('')
if sel == 'Y':
    pyperclip.copy(structure)
elif sel == 'N':
    print('Done')