not the desirable output [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
the expected out put was
1 1
2 2
3 3
4 4
5 5
but the output I got is
1
1 2
2 3
3 4
4 5
5
for num in numlist:
print(num)
print(num,end=' ')
I tried to execute this python code in python interpreter and got the wrong output

Every print has an end. Unless you overwrite what print should end in, it ends in a new line. In your first print, you don't overwrite end, so you get a new line. In your second print command, you do overwrite end with a single whitespace.
What you get is this order:
1st print NEWLINE
2nd print SPACE 1st print NEWLINE
2nd print SPACE 1st print NEWLINE
...
You get the exact output you are asking for. I suggest you read the entire Input/Output section of this geeksforgeeks page: https://www.geeksforgeeks.org/taking-input-in-python/?ref=lbp

newline ('\n') is the default end character. Therefore the first call to print() will emit the value of num followed by newline.
In the second print you override the end character with space (' ') so no newline will be emitted.
When you print multiple values, the default separator is a space. This means that you can achieve your objective with:
for num in numlist:
print(num, num)

Related

In Python how to fetch 10 characters after a specific string in a text file [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 5 years ago.
Improve this question
I am trying to read input form a text file which has around 1000 lines of data like:
SMSfrom+447919311433to+408640236167
Phonecallfrom+652578614377to+173972991459
Output desired:
+447919311433
I wanted to fetch all UK phone numbers from the text file and am trying to fetch 10 charecters after searching the string +44 in the file.I am using python 2.7.5 .Please help.
With a txt file called log.txt, with contents:
SMSfrom+447919311433to+408640236167
Phonecallfrom+652578614377to+173972991459
we can open the file for reading with:
open("log.txt", "r")
Then, we can loop through each line in the file and try and extract the data you want.
regular expression solution:
To extract the data from a line, we can use a regular expression. If you have never encountered these before, they are ways of extracting data from a string using a pattern which consists of different special characters.
So that we can pickup 2 UK phone numbers in one line, we will use the re.findall function on the line. I created the following pattern to pickup all UK phone numbers:
\+44\d{10}
It works by searching for the string '+44' with an escaping '\' on the '+' special character, and then taking 10 digits after that with \d{10} (the \d means a digit and the {10} means 10 of them).
We can then put this expression inside a loop which will add each phone number to a list. As re.findall returns a list as well, we need to concatenate these lists instead of appending. We do this with the '+' operand (or more simply with +=).
Making the code that will pickup all UK phone numbers in the file:
import re
numbers = []
with open("log.txt", "r") as f:
for line in f:
numbers += re.findall("\+44\d{10}", line)
which for your 2 line file in the question, only gives one phone number in numbers:
['+447919311433']
if-statement solution:
this solution will NOT pickup the second UK phone number if it is from a UK and to a UK number as pointed out by Nick as index() returns only the first occurrence
To extract the data from a line, we must first test if the string: '+44' is in the line and, if it is, we want to find the index of '+44' in the line and add the 10 characters after that index to a list of numbers (note that the .index() method returns the index of the start of the string, so we need to take 13 (10 + 3 for '+44') characters after the index).
The code for this would look like:
numbers = []
with open("log.txt", "r") as f:
for line in f:
if '+44' in line:
start = line.index('+44')
numbers.append(line[start:start+13])
which will add to the list: numbers, which will finish with contents:
['+447919311433']
Obviously, if you used your 1000 lined txt file, then this list would be much longer!
Hope this helps!
String with phone numbers:
string="+440123456789+341234567890+442345678901+443456789012"
You apply this algorithm to it:
for i in range(0,len(string)):
if string[i] == "+" and string[i+1] == "4" and string[i+2] == "4":
number = string[i:i+13]
print(number)

Add a space in between loop outputs using .format: Python 3

I am trying to create a for loop where the user inputs a number n and the output provides the range of values from n to n+6. This needs to all be printed in one row and be right aligned with spaces in between value outputs but no space at the end or start of the output.
So far this is what I've come up with:
n=eval(input("Enter the start number: "))
for n in range(n,n+7):
print("{0:>2}".format(n),end=" ")
However, this results in the following output:
-2 -1 0 1 2 3 4 <EOL>
When the output I want needs to look similar but without the space at the end, like so:
-2 -1 0 1 2 3 4<EOL>
How can I add spaces between values without adding an additional space to the final term?
There are 3 recommendations I could make:
use end="" and insert the whitespaces manually
create a string and print after the loop:
s = ""
for n in range(n, n+7):
s+= str(n)+ " "
s = s[:-1] #remove the ending whitespace
print(s)
which I recommend: Using sys.stdout.write instead print:
print only displays the message after a linebreak was printed. So if there is a long calculation in the loop and there is end=" " you will only see the resulr at the end of all calculations. Use sys.stdout instead
for n in range(n, n+7):
if n < n+7:
sys.stdout.write(str(n)+" ")
else:
sys.stdout.write(str(n))
sys.stdour.flush() #flush output to console
Edit: I evolved a bit and this is what I'd use nowadays:
4. message = " ".join(range(n, n+7))
This puts spaces between all elements of a list. You can choose any separation character instead of a space (or multiple characters).

End = ' ' in nested loop [duplicate]

This question already has answers here:
Meaning of end='' in the statement print("\t",end='')? [duplicate]
(2 answers)
Closed 4 years ago.
I just started python few days ago, and didn't really understand end =' ' in nested loop. Can anybody explain me this
count=0
for i in range(10):
for j in range(0, i):
print (count, end='')
count +=1
print()
'' is the "empty string" (e.g. nothing). The "end" parameter is what gets printed after the preceding set of variables. The default value of "end" is the newline (i.e. subsequent print statements will begin on a new line). By specifying '', the loop above will literally print out
1
22
333
4444
55555
666666
7777777
88888888
999999999
with each inner loop result on a single line. Without the end='' param, it would get printed out as:
1
2
2
3
3
3
...
9
9
The final print() at the end of the inner loop, just prints a new line.
End is print function keyword argument. The default value of end is \n meaning that after the print statement it will print a new line. If you redefine end, print will output your redefined value after using.
print("123", end="=")
#prints '123='
'' means empty string, so, you wil get output with no delimiters.
The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed,
prints an according Count value and stays in the same line. If you left out the end='' each time a newline would be printed
We learn everything by doing, So lets suppose we remove that end="" at the end of the print function. So you code will look like this
count=0
for i in range(10):
for j in range(0, i):
print (count)
count +=1
print()
and the output will be as
1
2
2
3
3
3
...
Now this output may or may not be your desired output depending on where you want to use the code
you may be wondering why this happens when you have not specified python to add a new line, its due to the fact that print function add new line character at the end of the output by default so if you doesnot want that to happen add end="" for the output line end with a empty string or nothing. likewise use end="/t" for tab end="." to end the print statement with a period and so on.
ProTip
use
print()
when ever you want a new line in or out of a loop

Change color for certain words in a sentence [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a string in Python.
string ="Marry had. A little lamb"
and a string that contains some words from the first string
part="had. lamb"
I need to print the first string and change color for the words from the second string.
Where I am now.
class c:
blue = '\033[94m'
red = '\033[93m'
string ="Marry had. A little lamb"
part =" had. lamb"
pos= [string.split().index(t) for t in part.split()]
print(pos) # prints [1, 4]
print c.blue+(string) #prints string in blue needs to print 1 and 4 from pos in red
It looks like you are overcomplicating things. A split to change parts into a list, followed by iterating over the individual words in string and testing if they appear in parts, seems all that's necessary:
>>> partwords = part.split()
>>> for w in string.split():
... if w in partwords:
... print c.red+w,
... else:
... print c.blue+w,
Result (and yes, your escape code is for yellow, not for red):

How to print on the same line in Python [duplicate]

This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed last month.
Is it possible to print text on the same line in Python?
For instance, instead of having
1
2
3
I would have
1 2 3
Thanks in advance!
Assuming this is Python 2...
print '1',
print '2',
print '3'
Will output...
1 2 3
The comma (,) tells Python to not print a new line.
Otherwise, if this is Python 3, use the end argument in the print function.
for i in (1, 2, 3):
print(str(i), end=' ') # change end from '\n' (newline) to a space.
Will output...
1 2 3
Removing the newline character from print function.
Because the print function automatically adds a newline character to the string that is passed, you would need to remove it by using the "end=" at the end of a string.
SAMPLE BELOW:
print('Hello')
print('World')
Result below.
Hello
World
SAMPLE Of "end=" being used to remove the "newline" character.
print('Hello', end= ' ')
print('World')
Result below.
Hello World
By adding the ' ' two single quotation marks you create the space between the two words, Hello and World, (Hello' 'World') - I believe this is called a "blank string".
when putting a separator (comma) your problem is easily fixed. But obviously I'm over four years too late.
print(1, 2, 3)

Categories