When should \n in Python 3.x be used? [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I understand that \n in Python 3.x begins a newline in a string.
But in this exemplar case:
answer = int(input("What's 7 x 3?\n"))
if answer == 21:
print("That's correct.")
else:
print("That's incorrect.")
should it be used and why? Also, in what other situations would \n be used?

\n is the standard newline character across most operating systems. In python, as well as most other programming languages, \n is used to start a newline whether you are aware of it or not. In python for example
print "hello world"
actually appends a newline character to the string in question and prints it.
print "hello world\n",
will yield the same exact output as the "," prevents the newline character from being added. In python there are very few reasons to use \n as it is generally added for you. The two main cases where one is explicitly interesting in the newline character is:
Writing to files
Removing newlines when reading from files
When writing to a file, one needs to explicitly use \n to generate newlines in the file. For example:
with open("example.txt","w") as fout:
fout.write("hello world\n")
and when reading in from a file:
with open("example.txt","r") as fin:
for line in fin:
print line.rstrip("\n")

If you want your terminal session with the program to look like:
What's 7 x 3?
21
That's correct.
then you should put the newline as you have. If you want it to look like:
What's 7 x 3? 21
That's correct.
then you should put a space at the end of the prompt instead of newline:
answer = int(input("What's 7 x 3? "))

Related

How to remove matching letters in a string that come after a comma? Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 months ago.
Improve this question
I am working on a coding challenge that takes user input removes matching letters that come after a comma and scrubs the white space. For the life of me I can’t figure it out.
For example the user inputs:
Hello World, wea
Output would be:
Hllo orld
Any direction on how to solve this would be greatly appreciated it is driving me crazy.
Try using a simple for loop that iterates across the phrase and places characters that don't appear after the comma into a separate string. Then the separate string is the result once the for loop has finished.
There are tons of different ways of achieving this, this way is fairly easy to understand though.
text = "Hello World, wea"
phrase, chars = text.split(",") # split the text by the comma
chars = chars.strip() # remove whitespace from second part
output = "" # separate string to collect chars
for letter in phrase:
if letter.lower() not in chars: # check lowercased letters
output += letter
print(output)
output
Hllo orld

Execute multiline code with tabs from input() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
Consider the following code:
code = input()
eval(code)
If I run it and type
> print(10)
It will get executed and print "10"
My question is when the code needs an indent, such as:
> for i in range(10):
> print(i)
How can I receive this code with input() (notice that I have to keep the indent) so that I can use eval() to run it?
If i understand correctly you want to be able to get python code using input() with tabs included.
the post
How to read multiple lines of raw input? tells us that we can get multiline input with
code = '\n'.join(iter(input, ''))
But after trying that myself I noticed that exec(code) didn't work because tabs were omitted from the input.
So here's a function that reads character directly and stops when it reads a given string
(here it's 2 newlines so you have to press ENTER twice to stop)
import sys
def input_until(sentinel):
text = ""
while not text.endswith(sentinel):
text += sys.stdin.read(1) # read 1 character from stdin
# remove the stop string from the result
return text[:-len(sentinel)]
code = input_until("\n\n")
exec(code)
I've tested it on https://replit.com/languages/python3 and it seems to work !
What's your use case here?
If you want to run the string in eval(), do you consider this?
new_string_name = "for i in range(10):\n eval(a)"
or
new_string_name = " eval()"
But if you don't want to follow the indentation rules (4 characters, no tabs), you can use
new_string_name = "for i in range(10):\n\teval(a)"
or
new_string_name = "\teval(a)"

is it correct? i hope someone can help me hehe [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Write a Python program that will search for lines that start with 'F', followed by 2 characters, followed by 'm:' using the mbox-short.txt text file.
Write a Python program that will search for lines that start with From and have an # sign
My code:
import re
file_hand = open("mbox-short.txt")
for line in file_hand:
line = line.rstrip()
if re.search('From:', line):
print(line)
your code seems to lack the actual regular expression that will find the result you are looking for. If I understand correctly, your aim is to find lines starting with F, followed by ANY two characters. If this is the case, you wish to print the line to the terminal. Let me guide you:
import re
file_hand = open("mbox-short.txt")
for line in file_hand: #NB: After a new scope is entered, use indentation
result = re.search("$f..", line) #pattern, search string
#$ matches character before the first in a line
#. matches 1 occurence of any character
if result.group() != "": #access result of re.search with group() method
print(line)
I trust you can follow this. If you need capital F, I will leave it as a homework exercise for you to find out how to do the capital F.
You can practice with regexp here:
https://regexr.com/
Or read more about it here:
https://www.youtube.com/watch?v=rhzKDrUiJVk
I think you didn't ask your question clear enough for everybody to understand. Also, insert your code for better readability ('Code Sample'). I already did that with your code, so you can have a look at that.

How to merge lines split with "\" at the very end with Python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am now parsing some text. Some lines are very long such that they are splitted into several sub-lines with a "\" at the very end.
I try to use regular expression to merge these sub-lines. However the escaped character "\n" and "\" make me confusing.
Can someone show me how to accomplish this task with Python?
str1 = """This is a sample with slash \
also some new line characters
This line becomes the second element \
with this line also
"""
print str1.split('\n')
You probably mean this:
import re
def reg():
st = r"hi i have a really long line so i have a \ im cool now \n"
print re.sub(r'\\{1} ', '', st)
reg()
Find some way that '\' differs from '\n'. I've used a space after '\'.
If you're reading text from a file like
line 1 \
continuation of line 1
Then what you need to do is replace the "backslash + line feed" pair of characters with an empty string:
content = open('myfile.txt').read()
fixed_content = content.replace('\\\n', '')
From the sound of it you can use the srt.split('\n') function. If you are reading lines from a file just use readlines and it will split them into a list for you.
f=open('file.txt','rb')
lines=f.readlines()

How to enter a large string in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm working in a program that needs to compare strings that have about 900 digits.
But whenever I enter them as
a = '01111111111111100000000000111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111010101000000000000000000000000000000011111111111111111111111111111111111111100000000000000000000000000000000000000000000111111111111111111111111111100001010101000010100'
Python only takes the first line as the string, and it says error.
In which way can I enter it so that Python takes the complete string?
Thanks
You mean you need to enter a multi-line string with newlines?
Use triple quoting:
a = '''This is the first line
and a second one too
hello world!
'''
Newlines are preserved, as is all whitespace.
If you didn't want to include newlines, use parenthesis around multiple strings:
a = (
'This is one string, '
'entirely without newlines, but it is one long '
'string nonetheless')
The Python compiler makes such consecutive strings (without anything but whitespace in between) into one long string object.
However, a 900 digit string is perhaps best stored in a separate file, not in your source code:
with open('digitsfile.txt', 'r') as infh:
a = infh.read().strip() # read all data, remove newline at the end
The Python compiler concatenates adjacent string literals. You just need to tell the compiler that the literals are adjacent.
a = (
'123'
'456'
'789'
)
print a
you can skip new line by \:
>>> num = '12345' \
... '67890'
>>> num
'1234567890'
Are you sure there is no carriage return in the string somewhere, that would cause an error.
Try enclosing the string in triple quotes
s = """really long strrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrring"""
and then echo it back
print s

Categories