Python using """ some data """ without printing newline - python

So what im trying to do is printing several data with """ """ my Question is if its possible that i can hold this without python printing it again and again im using the sys.stdout.write func with "\r" at the end but in the Console its still moving down. Does Somebody have an idea how to it with """ """ or another method?(Im using Python 2.7)

Thats not really what i want i want the stuff thats in the """ """ to be not moving in the console so that its not printed every time again want to stay in one place like this and not like this

In python 2 you can simply add comma to end of the statement to avoid adding "\n" to output.
print "Hello",
print "world",
The output will be Hello world.
Update:
Look here to read about escape codes.
Made a simple example for you:
import time
template = """
Line 1: [%d]
Line 2: [%d]
"""
prev_line_char = "\033[F"
k = 3
m = 4
while True:
print template % (k, m)
k += 1
m += 3
time.sleep(1)
for i in range(4):
print prev_line_char,

Related

code does not work in sublime text when using function with "return" statement [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 11 months ago.
I'm new to python programming, and as a beginner I want to start by using a code editor,
I choose sublime text 4 but I face this problem,
So help me please !
This is the code :
def return_string(your_string):
if len(your_string) >= 4:
new_string = your_string[0:2] + your_string[-2:]
return new_string
elif len(your_string) == 2:
new_string = your_string * 2
return new_string
elif len(your_string) < 2:
new_string = ""
return new_string
return_string("welcome")**
the expected output is "weme" but I get nothing in sublime text output (when I click Ctrl + B).
When I change return to print the code is executed properly.
By the way the code above works in vscode without any problem.
Python doesn't print outside the REPL normally, unless you explicitly tell it to. Add a call to print on your last line:
print(return_string('welcome'))
This is why adding an explicit print in your function works.
You can store the value into a variable first if you want to use it elsewhere:
result = return_string('welcome')
print(result)
Because "return string" returns a string, you must first save the data in a variable, which you may then use later in the program.
result_string = return_string("welcome")
print(result_string)

Python issue with replace statement?

I've been write this practice program for while now, the whole purpose of the code is to get user input and generate passwords, everything almost works, but the replace statements are driving me nuts. Maybe one of you smart programmers can help me, because I'm kinda new to this whole field of programming. The issue is that replace statement only seems to work with the first char in Strng, but not the others one. The other funcs blower the last run first and then the middle one runs.
def Manip(Strng):
#Strng = 'jayjay'
print (Strng.replace('j','h',1))
#Displays: 'hayjay'
print (Strng.replace('j','h',4))
#Displays: 'hayhay'
return
def Add_nums(Strng):
Size=len(str(Strng))
Total_per = str(Strng).count('%')
# Get The % Spots Position, So they only get replaced with numbers during permutation
currnt_Pos = 0
per = [] # % position per for percent
rGen = ''
for i in str(Strng):
if i == str('%'):
per.append(currnt_Pos)
currnt_Pos+=1
for num,pos in zip(str(self.ints),per):
rGen = Strng.replace(str(Strng[pos]),str(num),4);
return rGen
for pos in AlphaB: # DataBase Of The Positions Of Alphabets
for letter in self.alphas: #letters in The User Inputs
GenPass=(self.forms.replace(self.forms[pos],letter,int(pos)))
# Not Fully Formatted yet; you got something like Cat%%%, so you can use another function to change % to nums
# And use the permutations function to generate other passwrds and then
# continue to the rest of this for loop which will generate something like cat222 or cat333
Add_nums(GenPass) # The Function That will add numbers to the Cat%%%
print (rGen);exit()

How to replace text on python shell

I would like to make a program that will print out number values. I want it to display the number, then replace it with another number. A little like this:
val = 0
for looper in range(1, 10):
val += 1
print (val)
#Code to replace old number to new number
Thanks for helping!
If you want in-place update of the number, you can use \r.
import sys
val = 0
for looper in range(1, 10):
val += 1
sys.stdout.write("\r%d" % (val))
sys.stdout.flush()
time.sleep(1) # sleep added so that you can see the effect
Seems like you're looking for something to replace output in sys.stdout.
This is limited without using external libraries but you can do something like this:
import sys
import time
for number in xrange(10):
# put number in 'stdout'
sys.stdout.write(str(number))
# empty stdout (by default it waits for a new line)
sys.stdout.flush()
# display the number for some time
time.sleep(1)
# go back to beginning of input to override existing output
sys.stdout.write('\r')
I think you are taking about carriage return
use "\r" this with time.sleep(ms)
On Python 3, #Teemu Kurppa's answer could be written as:
import time
for i in range(1, 11):
print(i, end='\r', flush=True)
time.sleep(1)

Making string series in Python

I have a problem in Python I simply can't wrap my head around, even though it's fairly simple (I think).
I'm trying to make "string series". I don't really know what it's called, but it goes like this:
I want a function that makes strings that run in series, so that every time the functions get called it "counts" up once.
I have a list with "a-z0-9._-" (a to z, 0 to 9, dot, underscore, dash). And the first string I should receive from my method is aaaa, next time I call it, it should return aaab, next time aaac etc. until I reach ----
Also the length of the string is fixed for the script, but should be fairly easy to change.
(Before you look at my code, I would like to apologize if my code doesn't adhere to conventions; I started coding Python some days ago so I'm still a noob).
What I've got:
Generating my list of available characters
chars = []
for i in range(26):
chars.append(str(chr(i + 97)))
for i in range(10):
chars.append(str(i))
chars.append('.')
chars.append('_')
chars.append('-')
Getting the next string in the sequence
iterationCount = 0
nameLen = 3
charCounter = 1
def getString():
global charCounter, iterationCount
name = ''
for i in range(nameLen):
name += chars[((charCounter + (iterationCount % (nameLen - i) )) % len(chars))]
charCounter += 1
iterationCount += 1
return name
And it's the getString() function that needs to be fixed, specifically the way name gets build.
I have this feeling that it's possible by using the right "modulu hack" in the index, but I can't make it work as intended!
What you try to do can be done very easily using generators and itertools.product:
import itertools
def getString(length=4, characters='abcdefghijklmnopqrstuvwxyz0123456789._-'):
for s in itertools.product(characters, repeat=length):
yield ''.join(s)
for s in getString():
print(s)
aaaa
aaab
aaac
aaad
aaae
aaaf
...

Why does adding 1 print Kill my code (Python)?

I was playing with this sudoku solver, that I found.
Like quoted here it works perfect, but if I uncomment that single print a, that I commented out (line 13), then it stops before finding a full solution...?
import sys
from datetime import datetime # for datetime.now()
def same_row(i,j): return (i/9 == j/9)
def same_col(i,j): return (i-j) % 9 == 0
def same_block(i,j): return (i/27 == j/27 and i%9/3 == j%9/3)
def r(a):
i = a.find('.')
if i == -1: # All solved !
print a
else:
#print a
excluded_numbers = set()
for j in range(81):
if same_row(i,j) or same_col(i,j) or same_block(i,j):
excluded_numbers.add(a[j])
for m in '123456789':
if m not in excluded_numbers:
# At this point, m is not excluded by any row, column, or block, so let's place it and recurse
r(a[:i]+m+a[i+1:])
if __name__ == '__main__':
if len(sys.argv) == 2:
filI = open(sys.argv[1])
for pusI in filI:
pusI.strip()
print "pussle:\n",pusI
timStart = datetime.now()
r(pusI) # <- Calling the recursive solver ...
timEnd = datetime.now()
print "Duration (h:mm:ss.dddddd): "+str(timEnd-timStart)
else:
print str(len(sys.argv))
print 'Usage: python sudoku.py puzzle'
The program needs to be called with a file. That file should hold 1 sudoku per line.
For testing I used this:
25...1........8.6...3...4.1..48.6.9...9.4.8...1..29.4.9.53.7....6..5...7.........
QUESTION:
I can't understand how that single 'print a' manage to break the recursive loop, before it's done. Can anyone give an explanation?
Credit: I originally found the above sudoku solver code here:
http://www.scottkirkwood.com/2006/07/shortest-sudoku-solver-in-python.html
it's also shown here on StackOverflow:
Shortest Sudoku Solver in Python - How does it work?
It actually does find the solution.
I ran the program and get the solution
256491738471238569893765421534876192629143875718529643945387216162954387387612954
If you run with the uncommenting as you suggested and output that to a file:
python solver.py file.txt > output.txt
And search for the solution string, it is there. It's not the last line, for me it shows up 67% into the file.
The reason it does this is that the solver basically goes through a ton of combinations and it finds the solution but continues as long as there are any possible paths to go down to find a possible solution.

Categories