text = 'PYTHON'
for index in range(len(text)):
print(*text[:index + 1])
The * in the print function is producing a space between the characters on sys.stdout. Can someone please tell me what is it called and what does it actually do?
The print of * for a text is equal as printing print(text[0], text[1], ..., text[n]) and this is printing each part with a space between.
you can do
text = 'PYTHON'
for index in range(len(text))
print("".join(list(text)[:index + 1]))
or
text = 'PYTHON'
for index in range(len(text))
print(*text[:index + 1], sep='')
that will print each part without space in between.
Output
P
PY
PYT
PYTH
PYTHO
PYTHON
It is called an asterisk.
The asterisk passes all of the items in list into the print function call as separate arguments, without us even needing to know how many arguments are in the list.
You can read more about it here:
https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/
Related
I am attempting to create a loop that creates a file named "/tmp/newfile.txt" and creates 29 lines of text. Line 1 should read: "I see 0 sheep". For each line, 1 sheep should be added and a new line created to reflect that until 29 sheep (and lines) are reached.
x = 0
myDoc = myDoc.readfiles("/tmp/newfile.txt", "r+")
myDoc.write("I see" + str(x) + "sheep")
for line in myDoc.readfiles():
x = x + 1
myDoc.append(x)
print(myDoc)
if x == 30
break;
First, what I tried to do is create a new file and put it into a variable (myDoc) that would open it. I specified w+ so that I would have the ability to read the file and write on it. I gave the changing number a variable 'x'.
The function I intended to, for each line in the file, write "I see x sheep". Afterward, add 1 to the current value of x and append it so it's added to the file. After this, print it so I can see the line(s). Once that value reached 30, cease the loop because 29 is the number of lines I need.
My errors have to do with indentation and nothing being printed at all. I am extremely new to this.
Welcome to StackOverflow!
There seem to be a couple of issues in the code:
Indentation / Syntax Errors - It seems that you are using Python, which follows strict indentation and whitespace rules. An indent is inserted when you enter a new local scope / new control flow / enter an if/elif/else statement or a while or for loop, to separate it from the current scope.
You'd need to remove the space on the left side on line 3 and line 6.
Also, on line 8 there should be a colon(:) after the if x==30.
The mode used (w+) isn't going to work as expected.
This mode overwrites a file if it already exists and allows you to read and write to that file. Instead, you would need the r+ mode.
There's a great explanation & flowchart in this answer explaining the various file modes - https://stackoverflow.com/a/30566011/13307211
The for loop can't iterate over myDoc.
The open function gives a file object (TextIOWrapper), which can't be iterated over. You could use the myDoc.readfiles() method, which returns a list of lines present in the file and loop over that - for line in myDoc.readfiles().
printing myDoc and using .append() with myDoc wouldn't work as expected. It's representing a file object, which doesn't have an append method. Also, I feel like there might have been some mixed logic here - were you trying to iterate over myDoc like an array and hence pushing value to it?
I'd suggest removing the append part as the past value of x isn't going to be needed for what you want to do.
After applying the above, you should end up with code that looks like this -
x = 0
myDoc = open("./newfile.txt", "r+")
for line in myDoc.readlines():
myDoc.write("I see" + str(x) + "sheep\n")
x = x + 1
if x == 30:
break
Now, this doesn't exactly do what you want it to do...
The first thing we should do is update the for loop - a for loop should be structured in a way where it has a start, an end, and an increment, or it should iterate over a range of values. Python has a neat range function that allows you to iterate between values.
for x in range(1, 10):
print(x)
the above would print values from 1 to 10, excluding 10.
updating our for loop, we can change the code to -
myDoc = open("./newfile.txt", "r+")
for x in range(1, 30):
myDoc.write("I see" + str(x) + "sheep")
we could also use a while loop here -
myDoc = open("./newfile.txt", "r+")
for x in range(1, 30):
myDoc.write("I see" + str(x) + "sheep")
this makes the file but without the lines and without the right formatting. "I see " + str(x) + " sheep" should fix the sentence, but to print the string on multiple lines instead of the same line, you would need to use the newline character(\n) and add it at the end of the string -
myDoc = open("./newfile.txt", "r+")
for x in range(1, 30):
myDoc.write("I see" + str(x) + "sheep\n")
Beginning Python guy here. Have some code I need help with.
My main question here is in this bit of code we have 3 define statements for mm, yy, and yyyy.
In the 'hpds_folder =' statement it references 'dnb*{0}{1}' with the {0} and {1} being the 1st and 2nd input parameters.
mm = hadoop.date_part()['mm']
yy = hadoop.date_part()['yy']
yyyy = hadoop.date_part()['yyyy']
hdfs_folder = '/sandbox/US_MARKETING/COMMON_DATA/BAU/FILES/{0}/{1}'.format(yyyy, mm)
find_dnb = hadoop.file_find(file='dnb*{0}*{1}*'.format(mm, yy), folder = hadoop._xfer_in_hadoop['dnb'])
print('dnb*{0}*{1}*')
I'm assuming {0} and {1} should be what are populated by mm and yy respectively.
But when I try to print out the string for it:
print('dnb*{0}{1}')
I get just the literal 'dnb*{0}{1}' as output.
Shouldn't I get a month and a year?
On your print statement, you didn't format the text, so it wasn't replaced. the assignment on file happened once and didn't change the string literal for other locations.
Therefore, your print should be formatted as well:
print('dnb*{0}*{1}*'.format(mm, yy))
In Python3.6+, a new formatted strings were introduced, letting you do things such as:
print(f'dnb*{mm}*{yy}*')
Notice the f before the string mark. fstrings let you inject code to the string inside curly brackets {}.
You can also use it on your find_dnb line:
find_dnb = hadoop.file_find(file=f'dnb*{mm}*{yy}*', folder = hadoop._xfer_in_hadoop['dnb'])
I need this program to create a sheet as a list of strings of ' ' chars and distribute text strings (from a list) into it. I have already coded return statements in python 3 but this one keeps giving
return(riplns)
^
SyntaxError: invalid syntax
It's the return(riplns) on line 39. I want the function to create a number of random numbers (randint) inside a range built around another randint, coming from the function ripimg() that calls this one.
I see clearly where the program declares the list I want this return() to give me. I know its type. I see where I feed variables (of the int type) to it, through .append(). I know from internet research that SyntaxErrors on python's return() functions usually come from mistype but it doesn't seem the case.
#loads the asciified image ("/home/userX/Documents/Programmazione/Python projects/imgascii/myascify/ascimg4")
#creates a sheet "foglio1", same number of lines as the asciified image, and distributes text on it on a randomised line
#create the sheet foglio1
def create():
ref = open("/home/userX/Documents/Programmazione/Python projects/imgascii/myascify/ascimg4")
charcount = ""
field = []
for line in ref:
for c in line:
if c != '\n':
charcount += ' '
if c == '\n':
charcount += '*' #<--- YOU GONNA NEED TO MAKE THIS A SPACE IN A FOLLOWING FUNCTION IN THE WRITER.PY PROGRAM
for i in range(50):#<------- VALUE ADJUSTMENT FROM WRITER.PY GOES HERE(default : 50):
charcount += ' '
charcount += '\n'
break
for line in ref:
field.append(charcount)
return(field)
#turn text in a list of lines and trasforms the lines in a list of strings
def poemln():
txt = open("/home/gcg/Documents/Programmazione/Python projects/imgascii/writer/poem")
arrays = []
for line in txt:
arrays.append(line)
txt.close()
return(arrays)
#rander is to be called in ripimg()
def rander(rando, fldepth):
riplns = []
for i in range(fldepth):
riplns.append(randint((rando)-1,(rando)+1)
return(riplns) #<---- THIS RETURN GIVES SyntaxError upon execution
#opens a rip on the side of the image.
def ripimg():
upmost = randint(160, 168)
positions = []
fldepth = 52 #<-----value is manually input as in DISTRIB function.
positions = rander(upmost,fldepth)
return(positions)
I omitted the rest of the program, I believe these functions are enough to get the idea, please tell me if I need to add more.
You have incomplete set of previous line's parenthesis .
In this line:-
riplns.append(randint((rando)-1,(rando)+1)
You have to add one more brace at the end. This was causing error because python was reading things continuously and thought return statement to be a part of previous uncompleted line.
def digits_plus(test):
test=0
while (test<=3):
print str(test)+"+",
test = test+1
return()
digits_plus(3)
The output is:
0+ 1+ 2+ 3+
However i would like to get: 0+1+2+3+
Another method to do that would be to create a list of the numbers and then join them.
mylist = []
for num in range (1, 4):
mylist.append(str(num))
we get the list [1, 2, 3]
print '+'.join(mylist) + '+'
If you're stuck using Python 2.7, start your module with
from __future__ import print_function
Then instead of
print str(test)+"+",
use
print(str(test)+"+", end='')
You'll probably want to add a print() at the end (out of the loop!-) to get a new-line after you're done printing the rest.
You could also use the sys.stdout object to write output (to stdout) that you have more fine control over. This should let you output exactly and only the characters you tell it to (whereas print will do some automatic line endings and casting for you)
#!/usr/bin/env python
import sys
test = '0'
sys.stdout.write(str(test)+"+")
# Or my preferred string formatting method:
# (The '%s' implies a cast to string)
sys.stdout.write("%s+" % test)
# You probably don't need to explicitly do this,
# If you get unexpected (missing) output, you can
# explicitly send the output like
sys.stdout.flush()
This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
How to concatenate (join) items in a list to a single string
(11 answers)
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed 8 months ago.
The aim of the following program is to convert words in 4 characters from "This" to "T***", I have done the hard part getting that list and len working.
The problem is the program outputs the answer line by line, I wonder if there is anyway that I can store output back to a list and print it out as a whole sentence?
Thanks.
#Define function to translate imported list information
def translate(i):
if len(i) == 4: #Execute if the length of the text is 4
translate = i[0] + "***" #Return ***
return (translate)
else:
return (i) #Return original value
#User input sentense for translation
orgSent = input("Pleae enter a sentence:")
orgSent = orgSent.split (" ")
#Print lines
for i in orgSent:
print(translate(i))
On py 2.x you can add a , after print:
for i in orgSent:
print translate(i),
If you're on py 3.x, then try:
for i in orgSent:
print(translate(i),end=" ")
default value of end is a newline(\n), that's why each word gets printed on a new line.
Use a list comprehension and the join method:
translated = [translate(i) for i in orgSent]
print(' '.join(translated))
List comprehensions basically store the return values of functions in a list, exactly what you want. You could do something like this, for instance:
print([i**2 for i in range(5)])
# [0, 1, 4, 9, 16]
The map function could also be useful - it 'maps' a function to each element of an iterable. In Python 2, it returns a list. However in Python 3 (which I assume you're using) it returns a map object, which is also an iterable that you can pass into the join function.
translated = map(translate, orgSent)
The join method joins each element of the iterable inside the parentheses with the string before the .. For example:
lis = ['Hello', 'World!']
print(' '.join(lis))
# Hello World!
It's not limited to spaces, you could do something crazy like this:
print('foo'.join(lis))
# HellofooWorld!
sgeorge-mn:tmp sgeorge$ python s
Pleae enter a sentence:"my name is suku john george"
my n*** is s*** j*** george
You just need to print with ,. See last line of below pasted code part.
#Print lines
for i in orgSent:
print (translate(i)),
For your more understanding:
sgeorge-mn:~ sgeorge$ cat tmp.py
import sys
print "print without ending comma"
print "print without ending comma | ",
sys.stdout.write("print using sys.stdout.write ")
sgeorge-mn:~ sgeorge$ python tmp.py
print without ending comma
print without ending comma | print using sys.stdout.write sgeorge-mn:~ sgeorge$