'/' understood as a float? - python

I am looping through a pandas dataframe and trying to append the result on a conditional statement. However, my code seems to be posing a problem stopping me from append what I want although it prints fine but displays the error in the end. here is my code below:
counta=[]
for line in ipcm_perf['Alarms']:
if '/' in line:
print (line)
the error I get is the following :
2 for line in ipcm_perf['Alarms']:
----> 3 if ('/') in line:
4 print (line)
5
TypeError: argument of type 'float' is not iterable
I really do not know why Python is flagging that line. where's the float? Everything is being printed but with error at the bottom. It is stopping from appending.

your problem is that you are trying to check if there is a string (/) in a floating number (line), and Python does not like that.
That's because when you write "/" in some_string Python iterates through each char of some_string, but he can iterate through a floating number.
you can double check this by simply running:
if '/' in 3.14:
print("something")
output:
TypeError: argument of type 'float' is not iterable
I suppose that you're searching for a / because you've seen that somewhere in the column. If that's the case, it probably is in a string, and if that's the case, a quick&dirty way to clean your data can be:
if type(line) == str:
if "/" in line:
print(line)
else:
print("I am not a string")
and with line = 3.14, it returns:
I am not a string
and with line = "4/2", it returns:
I am a string

Related

How to read the value of a string stored in a text file, then convert to integer, and do math on value?

I've been writing Python code for only about 4 weeks. I'm writing a little text based game to learn and test everything I know. I can easily make this work with a value entered into the console as an integer, but for whatever reason I can't get my code to work with reading this value from a text file.
Earlier in the program, my code saves a value to a text file, just one value, then later it opens the same text file, over-writes the value with a new value based on a very simple calculation. That calculation is the first value, plus 5. I've spent a bunch of time reading on this site and going through my books and at this point I'm pretty sure I'm just missing something obvious.
The first piece of code that creates the doc and sets the value:
def set_hp(self):
f = open('player_hp.txt', 'w')
self.hitpoints = str(int(self.hitpoints))
f.write(self.hitpoints)
f.close()
This is the trouble section...I have commented the line with the problem.
def camp_fire():
print
print "You stop to build a fire and rest..."
print "Resting will restore your health."
print "You gather wood from the ground around you. You spark\n\
your flint against some tinder. A flame appears.\n\
You sit, and close your eyes in weariness. A peaceful calm takes you\n\
into sleep."
f = open('player_hp.txt', 'r')
orig_hp = f.readlines()
orig_hp = str(orig_hp)
f = open('player_hp.txt', 'w')
new_value = orig_hp + 5 ##this is where my code breaks
new_value = str(int(new_value))
f.write(new_value)
f.close()
print "You have gained 5 hitpoints from resting. Your new HP are {}.".format(new_value)
This is the error I get:
File "C:\Python27\Awaken03.py", line 300, in camp_fire
new_value = orig_hp + 5
TypeError: cannot concatenate 'str' and 'int' objects
I know you can't concatenate a string and an integer, but I keep trying different methods to convert the string to an integer to do the quick math, but I can't seem to get it right.
Error message is clear, you are trying to concatenate string with an integer. You should change the line from:
new_value = orig_hp + 5
To:
new_value = str(int(orig_hp) + 5)
Then you can use above value to write directly into file as a string as:
##new_value = str(int(new_value))## Skip this line
f.write(new_value)
f.readlines() returns a list of lines, in your case something like ['10']. So str(orig_hp) is a textual representation of this list, like '[\'10\']', which you won't be able to interpret as an integer.
You can just use f.read() to read the whole file at once in a string, which will be something like '10', and convert it to a integer:
orig_hp = int(f.read())

Syntax error: 002: on assigning values to variables python

Im writing a program for Uni to find all the palindromic primes, i have written out the program already but when i run it, my first input gets an error while trying to assign values to the variable.
please could someone tell me why this is the case!
start =input("Enter the start point N:")
starteval= eval(start)
endval = eval(input("Enter the end point M:"))
reverse=""
x=starteval+1
while x<endval:
reverse+=start[::-1]
evalreverse=eval(reverse)
if evalreverse==starteval:
if starteval==2 or starteval==3:
print(starteval)
elif starteval%2==0 or starteval%3==0:
pass
i=5
w=2
a=0
while i<=starteval:
if starteval%i==0:
break
else:
a=True
i+=2
if a==True:
print (starteval)
else:
pass
x+=x+1
the ouput i recieve is
"Enter the start point N:200
Enter the end point M:800
Traceback (most recent call last):
File "", line 1, in <module>
start =input("Enter the start point N:")
Syntax Error: 002: <string>, line 1, pos 3"
please and thank you!
Try instead of the first 3 lines to use:
starteval = int(raw_input("Enter the start point N:"))
endval = int(raw_input("Enter the end point M:"))
In Python 3 integer literals cannot begin with a zero:
>>> i = 002
File "<stdin>", line 1
i = 002
^
SyntaxError: invalid token
Because you are applying the eval function to your string input, Python attempts to parse your input as a valid Python expression, whcih is why you see the error you see.
It would make more sense to use int(input(...)) to get the integer (though you would still have to handle any exceptions raised when the user types a non-integer into your code). This has the advantage that it will accept the input that is causing you trouble in eval.
You could write a small intParsing function, that handles simple input parsing for you, then basically replace every "eval()" function of your code with intParsing().
Here is your edited code:
def intParsing(input_str):
str = ""
# Delete all chars, that are no digits (you could use a regex for that too)
for char in input_str.strip():
if char.isdigit():
str += char
# Now you only got digits in your string, cast your string to int now
r = int( str )
print "result of parsing input_str '", input_str, "': ", r
return r
start =raw_input("Enter the start point N:")
starteval= intParsing(start) # I edited this line
end = raw_input("Enter the end point M:") # I edited this line
endval =intParsing(end) # I edited this line
reverse=""
x=starteval+1
while x<endval:
reverse+=start[::-1]
evalreverse= intParsing(reverse) # I edited this line

How to Print this statment in to a txt file

I am trying to write a txt file but I am getting a TypeError.
How do I go about this? Here is my code below:
yesterdays_added = f1_set - f2_set
yesterdays_removed = f2_set -f1_set
with open('me{}{}{}.txt'.format(dt.year, '%02d' % dt.month, '%02d' % dt.day), 'w') as out:
for line in todays:
if line in yesterdays_added:
out.write( 'Removed', line.strip())
elif line in yesterdays_removed:
out.write ('Added', line.strip())
for line in yesterdays:
if line in yesterdays_added:
out.write ('Removed', line.strip())
elif line in yesterdays_removed:
out.write ('Added', line.strip())
This is the error I am getting:
out.write ('Added', line.strip())
TypeError: function takes exactly 1 argument (2 given)
You need to concatenate those together.
out.write("Added "+line.strip()) # Or out.write("Added {}".format(line.strip()))
For example,
>>> "Added "+"abc\n".strip()
'Added abc'
From The Python Docs
f.write(string) writes the contents of string to the file, returning
None.
Whenever in doubt, use help().
write(...)
write(str) -> None. Write string str to file.
This says that write() only takes in one argument. (Whereas you provide 2, hence the error)
As the error message suggests, write takes only one argument. If you want to write two things, make two calls to write, or concatenate them with +.
You received this error because the write method takes one argument of type string.
The writelines method, however, accepts one argument of type iterable.
The writelines method is the preferred method in this case, unless you would like to format the output string.
writelines example:
lines_to_write = ('Removed', line.strip(),)
open.writelines(lines_to_write)
write example:
line_to_write = '{0}...fancy formatting...{1}'.format('Removed', line.strip(),)
open.write(line_to_write)
Documentation:
http://docs.python.org/2/library/stdtypes.html#file.write
http://docs.python.org/2/library/stdtypes.html#file.writelines

Python import txt formatting

I have an Excel file with a list of numbers and I saved it as a .txt file and then went to say:
open_file = open('list_of_numbers.txt','r')
for number in open_file:
number = int(number)
while x < 20000:
if (x > number):
print number
x = x + 100
y = y + 100
And I received this error message:
ValueError: invalid literal for int() with base 10: '2100.00\r\n'
How can I strip the ' and the \r\n'?
My ultimate goal is to create another column next to the column of numbers and, if the number is 145 for example,
145, '100-199'
167, '100-199'
1167, '1100-1199'
that sort of output.
Let's put it as an answer. The problem is not \r\n. The problem is that you try to parse string that contains a float value as an integer. See (no line feed, new line characters):
>>> int("2100.00")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2100.00'
(as you can see, the quotation marks ' are not part of the value, they just indicate that you are dealing with a string)
whereas
>>> int("2100\r\n")
2100
The documentation says:
If the argument is a string, it must contain a possibly signed decimal number representable as a Python integer, possibly embedded in whitespace.
where the Python integer literal definition can be found here.
Solution:
Use float:
>>> float("2100.00\r\n")
2100.0
then you can convert it to an integer if you want to (also consider round):
>>> int(float("2100.00\r\n"))
2100
Converting a float value to integer works (from the documentation):
Conversion of floating point numbers to integers truncates (towards zero).
To address your immediate problem, go with the answer by #Felix Kling.
If you are interested in your FUTURE problems, please read on.
(1) That \r is not part of the problem IN THIS PARTICULAR CASE, but is intriguing: Are you creating the file on Windows and reading it on Linux/OSX/etc? If so, you should open your text file with "rU" (universal newlines), so that the input line on Python has only the \n.
(2) In any case, it's a very good idea to do line = line.rstrip('\n') ... otherwise, depending on how you split up the lines, you may end up with your last field containing an unwanted \n.
(3) You may prefer to use xlrd to read from an Excel file directly -- this saves all sorts of hassles. [Dis]claimer: I'm the author of xlrd.
Try this:
number = int(number.strip(string.whitespace + "'"))
You will need to add import string to the beginning of the your script. See also: http://docs.python.org/library/stdtypes.html#str.strip

How to append two strings in Python?

I have done this operation millions of times, just using the + operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from the command-line it doesn't!
The list is:
["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&\r", "DUM'&\r"]
I want to discard the first and the last elements, the code is:
ediMsg = ""
count = 1
print "extract_the_info, lineList ",lineList
print "extract_the_info, len(lineList) ",len(lineList)
while (count < (len(lineList)-1)):
temp = ""
# ediMsg = ediMsg+str(lineList[count])
# print "Count "+str(count)+" ediMsg ",ediMsg
print "line value : ",lineList[count]
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg : ",ediMsg
count += 1
print "count ",count
Look at the output:
extract_the_info, lineList ["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&\r", "DUM'&\r"]
extract_the_info, len(lineList) 8
line value : ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&
ediMsg : ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&
count 2
line value : DUM'&
DUM'& : ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&
count 3
Why is it doing so!?
While the two answers are correct (use " ".join()), your problem (besides very ugly python code) is this:
Your strings end in "\r", which is a carriage return. Everything is fine, but when you print to the console, "\r" will make printing continue from the start of the same line, hence overwrite what was written on that line so far.
You should use the following and forget about this nightmare:
''.join(list_of_strings)
The problem is not with the concatenation of the strings (although that could use some cleaning up), but in your printing. The \r in your string has a special meaning and will overwrite previously printed strings.
Use repr(), as such:
...
print "line value : ", repr(lineList[count])
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg : ", repr(ediMsg)
...
to print out your result, that will make sure any special characters doesn't mess up the output.
'\r' is the carriage return character. When you're printing out a string, a '\r' will cause the next characters to go at the start of the line.
Change this:
print "ediMsg : ",ediMsg
to:
print "ediMsg : ",repr(ediMsg)
and you will see the embedded \r values.
And while your code works, please change it to the one-liner:
ediMsg = ' '.join(lineList[1:-1])
Your problem is printing, and it is not string manipulation. Try using '\n' as last char instead of '\r' in each string in:
lineList = [
"UNH+1+TCCARQ:08:2:1A+%CONVID%'&\r",
"ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r",
"DUM'&\r",
"FPT+CC::::::::N'&\r",
"CCD+CA:5132839000000027:0450'&\r",
"CPY+++AF'&\r",
"MON+712:1.00:EUR'&\r",
"UNT+8+1'\r"
]
I just gave it a quick look. It seems your problem arises when you are printing the text. I haven't done such things for a long time, but probably you only get the last line when you print. If you check the actual variable, I'm sure you'll find that the value is correct.
By last line, I'm talking about the \r you got in the text strings.

Categories

Resources