2016-10-02 63 views
0

基本上我從https://en.wikipedia.org/wiki/List_of_lists_of_lists複製了一大堆列表到我的剪貼板中。 當我運行我的程序時,它會在每行之後添加項目符號。(Python)幫助修改剪貼板中的字符串

例如:

Lists of Iranian films 

會轉換成:

•• Lists of Iranian films •• 

等等。該程序適用於在行之前添加子彈的情況,但當我將它們放在它之後時,它只打印一個不帶任何換行符的長字符串。誰能告訴我我做錯了什麼?

下面的代碼:

#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) 

在我的剪貼板:

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 

剪貼板粘貼在記事本:

••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•• 
+0

你的問題是什麼?什麼是「文字」的類型?它是'str'元素的'list'嗎? – blacksite

+0

對不起,這個類型是一個複製到剪貼板的字符串。 – tadm123

回答

1

做一個小的變化,以您的代碼(使用os.linesep代替'\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) 

通常,「新行」是指任何的字符集通常被解釋爲信令新行,其可包括:在上DOS/Windows的

  • CR

    • CR LF在Unix上老的Mac
    • LF變種,包括現代的Mac

    CR是回車ASCII字符(代碼0X0D),通常表示爲\ r。 LF是換行符(代碼0x0A),通常表示爲\ n。

    而且,這樣說的:https://blog.codinghorror.com/the-great-newline-schism/

    我只是想讓你寫一個平臺無關的解決方案。因此os.linesep

  • +0

    非常感謝..這是工作。你能告訴我什麼是我做錯了嗎?非常奇怪的是它不適用於'\ n'字符。 – tadm123

    +0

    我明白了......再次感謝。 – tadm123