I want to create a Python program which takes in multiple lines of user input. For example:
This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.
How can I take in multiple lines of raw input?
sentinel = '' # ends when this string is seen
for line in iter(input, sentinel):
pass # do things here
To get every line as a string you can do:
'\n'.join(iter(input, sentinel))
Python 2:
'\n'.join(iter(raw_input, sentinel))
Alternatively, you can try sys.stdin.read() that returns the whole input until EOF:
import sys
s = sys.stdin.read()
print(s)
Keep reading lines until the user enters an empty line (or change stopword to something else)
text = ""
stopword = ""
while True:
line = raw_input()
if line.strip() == stopword:
break
text += "%s\n" % line
print text
Just extending this answer https://stackoverflow.com/a/11664652/4476612
instead of any stop word you can just check whether a line is there or not
content = []
while True:
line = raw_input()
if line:
content.append(line)
else:
break
you will get the lines in a list and then join with \n to get in your format.
print '\n'.join(content)
Try this
import sys
lines = sys.stdin.read().splitlines()
print(lines)
INPUT:
1
2
3
4
OUTPUT:
['1', '2', '3', '4']
*I struggled with this question myself for such a long time, because I wanted to find a way to read multiple lines of user input without the user having to terminate it with Control D (or a stop word).
In the end i found a way in Python3, using the pyperclip module (which you'll have to install using pip install)
Following is an example that takes a list of IPs
*
import pyperclip
lines = 0
while True:
lines = lines + 1 #counts iterations of the while loop.
text = pyperclip.paste()
linecount = text.count('\n')+1 #counts lines in clipboard content.
if lines <= linecount: # aslong as the while loop hasn't iterated as many times as there are lines in the clipboard.
ipaddress = input()
print(ipaddress)
else:
break
For me this does exactly what I was looking for; take multiple lines of input, do the actions that are needed (here a simple print) and then break the loop when the last line was handled. Hope it can be equally helpful to you too.
sys.stdin.read() can be used to take multiline input from user. For example
>>> import sys
>>> data = sys.stdin.read()
line one
line two
line three
<<Ctrl+d>>
>>> for line in data.split(sep='\n'):
print(line)
o/p:line one
line two
line three
The easiest way to read multiple lines from a prompt/console when you know exact number of lines you want your python to read, is list comprehension.
lists = [ input() for i in range(2)]
The code above reads 2 lines. And save inputs in a list.
Its the best way for writing the code in python >3.5 version
a= int(input())
if a:
list1.append(a)
else:
break
even if you want to put a limit for the number of values you can go like
while s>0:
a= int(input())
if a:
list1.append(a)
else:
break
s=s-1
A more cleaner way (without stop word hack or CTRL+D) is to use Python Prompt Toolkit
We can then do:
from prompt_toolkit import prompt
if __name__ == '__main__':
answer = prompt('Paste your huge long input: ')
print('You said: %s' % answer)
It input handling is pretty efficient even with long multiline inputs.
The Python Prompt Toolkit is actually a great answer, but the example above doesn't really show it. A better example is get-multiline-input.py from the examples directory:
#!/usr/bin/env python
from prompt_toolkit import prompt
from prompt_toolkit.formatted_text import HTML
def prompt_continuation(width, line_number, wrap_count):
"""
The continuation: display line numbers and '->' before soft wraps.
Notice that we can return any kind of formatted text from here.
The prompt continuation doesn't have to be the same width as the prompt
which is displayed before the first line, but in this example we choose to
align them. The `width` input that we receive here represents the width of
the prompt.
"""
if wrap_count > 0:
return " " * (width - 3) + "-> "
else:
text = ("- %i - " % (line_number + 1)).rjust(width)
return HTML("<strong>%s</strong>") % text
if __name__ == "__main__":
print("Press [Meta+Enter] or [Esc] followed by [Enter] to accept input.")
answer = prompt(
"Multiline input: ", multiline=True, prompt_continuation=prompt_continuation
)
print("You said: %s" % answer)
Using this code you get multiline input in which each line can be edited even after subsequent lines are entered. There are some nice additional features, too, such as line numbers. The input is ended by hitting the escape key and then the enter key:
~/Desktop ❯ py prompt.py
Press [Meta+Enter] or [Esc] followed by [Enter] to accept input.
Multiline input: first line of text, then enter
- 2 - second line of text, then enter
- 3 - third line of text, arrow keys work to move around, enter
- 4 - and lines can be edited as desired, until you
- 5 - press the escape key and then the enter key
You said: first line of text, then enter
second line of text, then enter
third line of text, arrow keys work to move around, enter
and lines can be edited as desired, until you
press the escape key and then the enter key
~/Desktop ❯
How do you like this? I mimicked telnet.
The snippet is highly self-explanatory :)
#!/usr/bin/env python3
my_msg = input('Message? (End Message with <return>.<return>) \n>> ')
each_line = ''
while not each_line == '.':
each_line = input('>> ')
my_msg += f'\n{each_line}'
my_msg = my_msg[:-1] # Remove unwanted period.
print(f'Your Message:\n{my_msg}')
With Python 3, you can assign each line to data:
while data := input():
print("line", data)
Simple, do
lst = [x for x in input("Enter numbers seperated by spaces").split("\n")]
line = input("Please enter lines: ")
lines = ""
while line:
lines += "\n" + line
line = input()
print(lines)
def sentence_maker(phrase):
return phrase
results = []
while True:
user_input = input("What's on your mind: ")
if user_input == '\end':
break
else:
results.append(sentence_maker(user_input))
print('\n'.join(map(str, results)))
Related
So I want to make this script look for a word, which you can determine, and its line number. I want it to print out the text in this line and the two following ones. How do I code the last part (print the next three lines)?
def search_passwords():
file = open("D:\\Libaries\\Documents\\resources_py\\pw.txt", "r")
print()
search = input("Enter service: ")
print()
for line in file:
if search in line:
print(the next three lines)
There are some corner cases that you did not mention.
What if multiple lines have the searching word? What is your expected behavior?
What if the line right after the matching line has the searching word?
How large is the file and could you load it in memory?
If there's only one matching, or there won't be any matching in the lines you print right after, then you can use a single counter
def search_passwords():
file = open("D:\\Libaries\\Documents\\resources_py\\pw.txt", "r")
print()
search = input("Enter service: ")
print()
counter = 0
for line in file:
if counter > 0:
counter -= 1
print(line)
if search in line:
counter = 2
print(line)
However, this will double print the lines if the following lines containing the searching word. You can of course make the second if elif, but then it will just ignore the following matching pattern.
And, if you only need the first or only appearance, you should break out of the loop once you print everything, not read the whole file.
Just like I said, you need to know the expected behavior and the requirement better, to write a solid program.
There could be a better solution but this is a bit more flexible with a nigher amount of following rows.
def search_passwords():
file = open("D:\\Libaries\\Documents\\resources_py\\pw.txt", "r")
print()
search = input("Enter service: ")
print()
counter = 3
found = False
for line in file:
if search in line:
found = True
if found:
if counter > 0:
counter -= 1
print(line, counter)
if counter == 0:
break
Yet another approach with not found error handling:
with open('file.txt', 'r') as f:
lines = [line.strip() for line in f.readlines()]
try:
i = lines.index(input('Enter service: '))
for j in range(i, i+3):
try:
print(lines[j])
except IndexError:
pass
except ValueError:
print('Service not found!')
I know that you can get a line from stdin with raw_input() function. But what if I don't know the number of lines that I will have to get?
I know that I can import 'sys' and then get all lines with a while loop, but is there any similar way to accomplish such a task using raw_input()?
This may be as simple as:
while(raw_input()):
#print "I received input"
#Do some processing here
#terminates when user hits enter without any text.
According to Python documentation, "" (an empty string) is treated as a False. So the loop terminates when user doesn't enters anything.
Or if you want the input entered by the user then you may use:
while True:
text = raw_input()
if not text:
break
#Do some processing here
Or if you want to specify some other breaking point then you could check for the condition inside the while loop as:
break_word = "q"
while True:
text = raw_input()
if text == break_word:
break
#Do some processing here
If you want to store your data consider using a list.
Read the values in a loop. If you get an empty line break out of the loop, else add the entered data to your list.
data = []
while True:
line = raw_input()
if not line:
break()
data.append(line)
You can use a list comp if you want to store all the lines:
lines = [line for line in iter(lambda: raw_input("enter line or 'q' to quit"), "q")]
Or using a loop:
for line in iter(lambda: raw_input("enter line or 'q' to quit"), "q"):
print(line)
The loop will break when a user enters q. The second arg to iter is a sentinel value, whatever you provide as the value can will break the loop when entered by the user.
Using iter is equivalent to:
while True:
inp = raw_input("Enter line or 'q' to quit")
if inp == "q":
break
Just more concise.
Not sure what im doing wrong here? the program asks for file name and reads the file but when it come to printing the encoded message it comes up blank. What am I missing, as if I change the phrase to just normal raw_input("enter message") the code will work, but this is not reading from the txt file.
letters = "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
cshift = int(input("Enter a number: "))
phrase = open(raw_input("file name: "), 'r')
newPhrase = ""
for l in phrase:
if l in letters:
pos = letters.index(l) + cshift
if pos > 25:
pos = pos-26
newPhrase += letters[pos]
else:
newPhrase += " "
print(newPhrase)
The problem here is that the for-loop on this line:
for l in phrase:
will return complete lines, not individual characters.
As such you will have to loop through individual characters from those lines as well, or read the file binary, or use functions on the file object that will read one character at a time.
You could simply do this:
for line in phrase:
for l in line:
... rest of your code here
The open function does not return a string, but a handle to the opened file from which strings can be read. You should search for information on how to read a file into a string in Python and then try it in a REPL to make sure it returns a string and not something else.
I need assistance for this problem I'm having. I'm trying to get my program to grab the first Letter from the first Word on every single line and print them in a single string.
For example if I type the following words in a block of text:
People like to eat pie for three reasons, it tastes delicious. The taste is unbelievable, next pie makes a
great dessert after dinner, finally pie is disgusting.
The result should be "Pg" this is a small example but you get the idea.
I started on the code but I'm clueless on where to go.
#Prompt the user to enter a block of text.
done = False
print("Enter as much text as you like. Type EOF on a separate line to finish.")
textInput = ""
while(done == False):
nextInput= input()
if nextInput== "EOF":
break
else:
textInput += nextInput
#Prompt the user to select an option from the Text Analyzer Menu.
print("Welcome to the Text Analyzer Menu! Select an option by typing a number"
"\n1. shortest word"
"\n2. longest word"
"\n3. most common word"
"\n4. left-column secret message!"
"\n5. fifth-words secret message!"
"\n6. word count"
"\n7. quit")
#Set option to 0.
option = 0
#Use the 'while' to keep looping until the user types in Option 7.
while option !=7:
option = int(input())
#I have trouble here on this section of the code.
#If the user selects Option 4, extract the first letter of the first word
#on each line and merge into s single string.
elif option == 4:
firstLetter = {}
for i in textInput.split():
if i < 1:
print(firstLetter)
You can store the inputs as a list, then get the first character from each list:
textInput = []
while(done == False):
nextInput= input()
if nextInput== "EOF":
break
else:
textInput.append(nextInput)
...
print ''.join(l[0] for l in textInput)
I'd start by making a list of lines instead of a single string:
print("Enter as much text as you like. Type EOF on a separate line to finish.")
lines = []
while True:
line = input()
if line == "EOF":
break
else:
lines.append(line)
Then, you can get the first letters with a loop:
letters = []
for line in lines:
first_letter = line[0]
letters.append(first_letter)
print(''.join(letters))
Or more concisely:
print(''.join([line[0] for line in lines]))
This is very simple:
with open('path/to/file') as infile:
firsts = []
for line in infile:
firsts.append(line.lstrip()[0])
print ''.join(firsts)
Of course, you could do the same thing with the following two-liner:
with open('path/to/file') as infile:
print ''.join(line.lstrip()[0] for line in infile)
Hope this helps
I'm having a little trouble with converting a text file to a list.
the text file is presented like this:
5658845
4520125
7895122
8777541
8451277
1302850
8080152
I have written code that takes user input and tries to determine if the user input is in the list. I am however having some trouble in searching the list as I can only get a result on the last result in the list, where am I going wrong?
def accountReader():
while True:
chargeInput = (raw_input ("Enter a charge account to be validated: "))
if chargeInput == '':
break
sys.exit
else:
chargeAccount = open('charge_accounts.txt', 'r')
line = chargeAccount.readline()
while line != '':
if chargeInput == line:
print chargeInput, 'was found in list.'
else:
print chargeInput, 'not found in list.'
break
chargeFile.close
A line-by-line breakdown:
def accountReader():
while True:
chargeInput = (raw_input ("Enter a charge account to be validated: "))
if chargeInput == '':
break
sys.exit
Ok, so far so good. You've created a loop that repeatedly asks the user for input and breaks when the user inputs nothing.
else:
chargeAccount = open('charge_accounts.txt', 'r')
line = chargeAccount.readline()
Here's where you start running into problems. readline reads a single line from chargeAccount and stores it in line. That means you can only test one line!
while line != '':
if chargeInput == line:
print chargeInput, 'was found in list.'
This further compounds your problem. If chargeInput == line, then this prints a message and then the loop repeats. Since there's nothing to break out of the loop, this will result in an infinite loop that constantly tests one single line from the file. Also, because each line from the file ends with a newline (\n), chargeInput == line will always yield false (thanks Steven Rumbalski for reminding me of this). Use .strip() (as suggested in matchw's answer), or, if you can tolerate partial matches, you could use Python's simple substring matching functionality: if chargeInput in line.
else:
print chargeInput, 'not found in list.'
break
chargeFile.close
And here, as sarnold pointed out, you've misnamed your file; furthermore, it's in a completely different block of code, which means that you repeatedly open chargeAccount files without closing any of them.
As you can see from matchw's post, there is a much simpler way to do what you're trying to do. But I think you'd do well to figure out how to write this code correctly in the style you've chosen. I'll give you one hint: there should be a line = chargeAccount.readline() inside the innermost while loop. Do you see why? Also, you should probably exit the loop when you succeed in finding a match, not when you fail. Then you should think about a way to test whether the search was a success after the innermost loop has completed.
i would read the list like this
chargeAccount = open('charge_accounts.txt', 'r')
accts = [line.strip() for line in chareAccount]
if chareInput in accts:
#do something
else:
#do something else
at the very least .strip() off the readline(), your line likely looks like '5658845\n'
UPDATE
so after testing what you have with my modification it works....except it repeats indef do to the while acct != ''
here is what I changed
chargeAccount = open('charge_accounts.txt', 'r')
accts = [line.strip() for line in chargeAccount]
while accts != '':
if chargeInput in accts:
#...
I would ditch the while loop altogether, it is either in the list or its not. no need to cycle through each line.