2012-01-28 153 views
8

有沒有辦法忽略通過raw_input輸入的數據中的換行符?我正在嘗試使用raw_input來輸入從電子表格複製並粘貼的字符串列表。問題在於看起來新的行字符會導致數據提前輸入。所有的空白空間都將被剝離,因此在輸入數據時刪除換行符會帶來額外的好處。這些數據需要直接通過終端提示輸入,而不是從文件中讀取。python raw_input忽略換行

這是我迄今所做的:一旦

names = raw_input('Shoot me some names partner: ') 

print 'What do you want to do?' 
print '1 - format names for program 1' 
print '2 - format names for program 2' 

first_act = raw_input('Enter choice: ') 

print names 
print first_act 

現在,當我運行這個輸入我投入了谷歌文檔電子表格中的假名字來測試,因爲我按下Shift + CTL + V ,沒有擊中輸入我得到這個:

[email protected]:~> python pythonproj/names.py 
Shoot me some names partner: abcd,efg,hijkl,mnop 
abcd,efg,hijkl,mnop 
abcd,efg,hijkl,mnop 
abcd,efg,hijkl,mnop 
abcd,efg,hijkl,mnop 
abcd,efg,hijkl,mnop 
abcd,efg,hijkl,mnop 
abcd,efg,hijkl,mnopWhat do you want to do? 
1 - format names for program 1 
2 - format names for program 2 
Enter choice: abcd,efg,hijkl,mnop 
abcd,efg,hijkl,mnop 
[email protected]:~> abcd,efg,hijkl,mnop 
If 'abcd,efg,hijkl,mnop' is not a typo you can use command-not-found to lookup the package that contains it, like this: 
cnf abcd,efg,hijkl,mnop 
[email protected]:~> abcd,efg,hijkl,mnop 
If 'abcd,efg,hijkl,mnop' is not a typo you can use command-not-found to lookup the package that contains it, like this: 
cnf abcd,efg,hijkl,mnop 
[email protected]:~> abcd,efg,hijkl,mnop 
If 'abcd,efg,hijkl,mnop' is not a typo you can use command-not-found to lookup the package that contains it, like this: 
cnf abcd,efg,hijkl,mnop 
[email protected]:~> abcd,efg,hijkl,mnop 
If 'abcd,efg,hijkl,mnop' is not a typo you can use command-not-found to lookup the package that contains it, like this: 
cnf abcd,efg,hijkl,mnop 
[email protected]:~> abcd,efg,hijkl,mnop 
If 'abcd,efg,hijkl,mnop' is not a typo you can use command-not-found to lookup the package that contains it, like this: 
cnf abcd,efg,hijkl,mnop 
[email protected]:~> abcd,efg,hijkl,mnop 

我很新的python,我不是迄今爲止最有經驗的程序員。這是python 2.7。

回答

1

我不確定你想問什麼,但是當你使用raw_input()時,它會去掉尾隨的換行符。

而醫生說也一樣。

如果提示參數存在,則將其寫入標準輸出 而不會出現尾隨換行符。該函數然後從輸入中讀取一行, 將其轉換爲字符串(剝離尾隨換行符),並返回 。讀取EOF時,引發EOFError。

7

因爲raw_input只需要一條線從輸入你需要創建一個循環:

names = [] 
print('Shoot me some names partner: ') 
while True: 
    try: 
     name = raw_input() 
    except KeyboardInterrupt: 
     break 
    names.append(name) 

print('What do you want to do?') 
print('1 - format names for program 1') 
print('2 - format names for program 2') 

first_act = raw_input('Enter choice: ') 

print(names) 
print(first_act) 

試運行:

Shoot me some names partner: 
name1 
name2 
^CWhat do you want to do? 
1 - format names for program 1 
2 - format names for program 2 
Enter choice: 1 
['name1', 'name2'] 
1 

注意我用^C(按Ctrl-C)這裏以指示輸入的結束。

+0

嗨,我該如何告訴python我已經完成了我的輸入?我嘗試了'^ c',但它不起作用。 – 2016-01-11 14:07:49