有没有办法忽略通过raw_input输入的数据中的换行符?我正在尝试使用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
现在,当我运行这个并输入虚拟名称时,我将其放入google doc电子表格进行测试,只要我按下shift + ctl + v,而不按Enter键,我就得到:
seth@linux-1337:~> 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
seth@linux-1337:~> 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
seth@linux-1337:~> 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
seth@linux-1337:~> 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
seth@linux-1337:~> 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
seth@linux-1337:~> 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
seth@linux-1337:~> abcd,efg,hijkl,mnop
我是python的新手,到目前为止我不是最有经验的程序员。这是python 2.7。
答案 0 :(得分: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)来表示输入结束。
答案 1 :(得分:1)
我不确定你要问的是什么,但是当你使用raw_input()时,它会删除一个尾随的换行符。
而且医生也这么说。
如果存在prompt参数,则将其写入标准输出 没有尾随换行符。然后该函数从输入中读取一行, 将其转换为字符串(剥离尾随换行符),然后返回 那。读取EOF时,会引发EOFError。