gpt4 book ai didi

Python raw_input 忽略换行符

转载 作者:太空狗 更新时间:2023-10-29 20:59:29 31 4
gpt4 key购买 nike

有没有办法忽略通过 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。

最佳答案

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

关于Python raw_input 忽略换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9047349/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com