I am trying to append characters in a string but I am getting problem with the loop. I don't know the command to append characters in the string:
import string
import random
def main():
generateRandomNumbers()
def generateRandomNumbers():
nameLength = 10
for i in range(nameLength)
x = random.choice(string.ascii_lowercase )
uname.append(x)
print (x)
size = 0
nameLength=0
if __name__ == "__main__":
main()
I am getting following error message:
File "Fl.py", line 8
for i in range(nameLength)
^ SyntaxError: invalid syntax
You are getting the syntax error because you are missing a colon at the end of your for loop. It should look like this:
for i in range(nameLength):
As Kenan has already said, I would recommend using the + operator to append to a string. This article has some decent examples that should put you on the right path.
Related
I am trying to generate the next code in Python:
atribute_name = 'atr1'
exec("list_%s = []", atribute_name)
So the expected result should be:
list_atr1 = []
But when I execute it I get the next error message:
TypeError: exec: arg 2 must be a dictionary or None
Why is it happening?
Instead of comma, you should replace it with % for string concatenation.
exec("list_%s = []" % atribute_name)
You are passing second argument for exec function.
Instead you just need to format your string.
Below sample code can help you.
atribute_name = 'atr1'
str1 = "list_%s = []" % atribute_name
print str1
exec(str1)
print list_atr1
#!/ usr/bin/python3
import sys
def main():
for line in sys.stdin:
line = line.split()
x = -1
for word in line:
if word[-1]==word[0] or word[x-1]==word[1]:
print(word)
main()
It also prints dots at the end of the sentences, why?
And words like 'cat' and 'moon' should also be out of the question. But it also prints these words.
Can someone point me in the right direction please?
I think your problem is because the second and second last characters of 'cat' are the same.
def main():
for line in sys.stdin:
line = line.split()
x = -1
for word in line:
if (word[-1]==word[0] and len(word)<=2) or (word[x-1]==word[1] and len(word)<=4):
print(word)
or something like that, depending on your preference.
This should get rid of that pesky cat, although moon stays.
It will also include words that use upper and lower case characters, so sadly not only will moon print but also Moon, MOon, mooN and moOn.
Edit: Forgot to test for one character words (a, I etc)
import sys
def main():
for line in sys.stdin:
line = line.split()
for word in line:
uword = word.lower()
if len(uword) > 1:
if uword[0:1]==uword[-1] or (uword[1:2]==uword[-2] and len(uword) > 3):
print(word)
main()
I got it guys, understood the question wrong. This prints the right words, that I got beforehand. That cleared things up for me. This is the right code but it still gives "sys.excepthook is missing". I run this code with another code that gives a space an newline. So every space between words becomes a newline:
cat cdb.sentences| python3 newline.py| python3 word.py |head -n 5
import sys
def main():
for line in sys.stdin:
line = line.split()
for word in line:
letterword = lw = word.lower()
if len(lw) > 1:
if lw[0:1]==lw[-1] and (lw[1:2]==lw[-2]):
print(word)
main()
import sys
def main():
for line in sys.stdin:
line = line.rstrip()
text = ""
for word in line:
if word in ' ':
text=text + '\n'
else:
text=text + word
print(text)
main()
It should give the 5 first words that have the same first, last letter, -2 and 1 letters. With an white line between each one of them. First i want to solve that hook.
Thx
You are not helping yourself by answering your own question with what is essentially a completely different question in an answer.
You should have closed your original off by accepting one of the answers, if one of them helped, which it looked like they did and then asked a new question.
However, the answer to your 2nd question/answer can be found here:
http://python.developermemo.com/7757_12807216/ and it is a brilliant answer
Synopsis:
The reason this is happening is that you're piping a nonzero amount of output from your Python script to something which never reads from standard input. You can get the same result by piping to any command which doesn't read standard input, such as
python testscript.py | cd .
Or for a simpler example, consider a script printer.py containing nothing more than
print 'abcde'
Then
python printer.py | python printer.py
will produce the same error.
The following however will trap the sys.excepthook error:
import sys
import logging
def log_uncaught_exceptions(exception_type, exception, tb):
logging.critical(''.join(traceback.format_tb(tb)))
logging.critical('{0}: {1}'.format(exception_type, exception))
sys.excepthook = log_uncaught_exceptions
print "abcdfe"
so I have some code such as:
print(csv[0])
Genes = csv[0]
OutPut.write(Genes)
OutPut.write(',')
OutPut.write(csv[1])
OutPut.write(',')
try:
OutPut.write(csv[2])
except IndexError:
print("No Lethality")
OutPut.write('\n')
Basically csv has 3 objects and they should print out as this:
atp,10101010,lethal
But for some reason, if csv[0] so the first value, begining with an 'l' it is printed as:
l
sfsf,1010101010,Lethal
I have tried using a for loop etc but I always get the same issue and all the other lines which start without an 'l' work perfectly.
Thanks
It's not clear from your description why you are seeing multiple lines, here's alternative logic that may help you diagnose the problem.
Try:
OutPut.write(','.join(csv))
OutPut.write('\n' if len(csv) == 3 else "No Lethality\n")
Or:
from __future__ import print_function
print(','.join(csv), file=Output)
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()
I'm writing a python program. The program calculates Latin Squares using two numbers the user enters on a previous page. But but an error keeps coming up, "cannot concatenate 'str' and 'list' objects" here is the program:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
import cgi
import cgitb
cgitb.enable()
def template(file, **vars):
return open(file, 'r').read() % vars
print "Content-type: text/html\n"
print
form = cgi.FieldStorage() # instantiate only once!
num_1 = form.getfirst('num_1')
num_2 = form.getfirst('num_2')
int1r = str(num_1)
int2r = str(num_2)
def calc_range(int2r, int1r):
start = range(int2r, int1r + 1)
end = range(1, int2r)
return start+end
int1 = int(int1r)
int2 = int(int2r)
out_str = ''
for i in range(0, int1):
first_line_num = (int2 + i) % int1
if first_line_num == 0:
first_line_num = int1
line = calc_range(first_line_num, int1)
out_str += line
print template('results.html', output=out_str, title="Latin Squares")
range returns a list object, so when you say
line = calc_range(first_line_num, int1)
You are assigning a list to line. This is why out_str += line throws the error.
You can use str() to convert a list to a string, or you can build up a string a different way to get the results you are looking for.
By doing out_str += line, you're trying to add a list (from calc_range) to a string. I don't even know what this is supposed to be doing, but that's where the problem lies.
You didn't say what line you're getting the error from, but I'm guessing it's:
out_str += line
The first variable is a string. The second is a list of numbers. You can't concatenate a list onto a string. I don't know what you're trying to do exactly, but how about:
out_str += ", ".join(line)
That will add the numbers joined by commas onto out_str.
calc_range() returns a list; however, you are attempting to add it to a string (out_str).
It looks like your code is unfinished - don't you want to do something with the range of numbers returned by calc_range()? Like, say, something with the form?
line = ''.join(num_1[index] for index in calc_range(first_line_num, int1))
I don't know if that's what you want - but maybe something like that?