Python原始输入忽略newlin

2024-06-26 14:45:46 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法忽略通过原始输入输入的数据中的换行符?我试图使用原始输入来输入从电子表格中复制和粘贴的字符串列表。问题是,新行字符似乎会导致过早输入数据。所有的空格都将被删除,因此在输入数据时删除换行符将是一个额外的好处。这些数据需要直接通过终端提示输入,而不是从文件中读取。

这就是我目前所做的:

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还不太熟悉,我也不是目前为止经验最丰富的程序员。这是Python2.7。


Tags: toyouifnamesislinuxnotcan
2条回答

因为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)来表示输入的结束。

我不知道您想问什么,但是当您使用raw_input()时,它会删除一个尾随的换行符。

医生也这么说。

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

相关问题 更多 >