This question already has answers here:
Python: String will not convert to float [duplicate]
(3 answers)
Closed 6 years ago.
I'm trying to extract a float from a line in a text file, but i can't for the life of me understand how to convert the number in the line (str) into a float
for line in fh:
if not line.startswith("A specific string") : continue
count = count + 1
#linevalue gets the numbers in the line that i'm interested in, so in order
#to have only the numeric value i tried getting rid of the other text in the line by only
# selecting that range (20:26
linevalue = line[20:26]
float(linevalue)
print type(linevalue)
print linevalue
the attempted conversion with float(linevalue) is not going through, the output of the program remains e.g:
<type 'str'> 0.4323
Can anyone help me understand what am I missing ?
Thank you very much for your time.
I think you want:
linevalue = float(linevalue)
You were correctly converting the string value to a float, but you weren't saving that value anywhere. (Calling float doesn't modify the existing variable; it returns a new value.)
Related
This question already has answers here:
Dynamically calculated zero padding in format string in python
(2 answers)
How do I pad a string with zeroes?
(19 answers)
Closed 9 months ago.
Sorry if this is a bit of a noob question. But moving on..
Say at the beginning of my code I set a variable, like this:
TestVar = 'A6'
But I later want it to print out as 000000A6
Or say it was
TestVar = 'C30'
I'd want it to print out as 00000C30
Basically always returning it with a length of 8
The reasoning for this is I've made a general script for modding a game, (I can link if asked) and you need to put in certain values which I want to have format automatically for ease of use. For example on running it'll print
Item ID Here:
And if you put in 166 it would convert the decimal number to hex which would be A6, however in order to be usable for all values (not just ones that are 2 digits once converted) I'm trying to make it detect it's length and format it with the 0s before.
Sorry if this doesnt make sense, in a simpler way of saying this, is there a way for it to detect the length of a variable? So for example in pseudo
TestVar = 'C30'
If TestVar length = 3
print('00000'+TestVar)
Print Result: 00000C30
Basically always returning it with a length of 8
That's what format strings do:
>>> print(f"{'C30':>08s}")
00000C30
As a sidenote, to output any number as 8-digit hex:
>>> print(f"{100:>08X}")
00000064
>>> print(f"{1024:>08X}")
00000400
See the documentation:
for f-strings (the f'I am an f-string' syntax);
for formatting syntax (the >08s and >08X thing).
Use string function rjust():
print(test.rjust(8,'0'))
The .zfill string method can be used.
For example:
s = 'C30'
s.zfill(8)
>>> '00000C30'
Try this code
txt = "A6"
x = txt.zfill(8)
print(x)
You can use string.zfill method
for example.
code = '3C0'
filledCode = code.zfill(8)
this method filled with zero the number of digit that you pass like a parameter
try something like this str.rjust() function
i = 1111
pad = '0'
n = 8
x = str(i).rjust(n, pad)
print(x) # 00001111
This question already has answers here:
Python: Strip off string quotes from binary number
(5 answers)
Closed 1 year ago.
b = 15
a = bin(b) # I want return as an integer not string
print(a, type(a)) # output is string, actually I want is integer
# output - 0b1111 <class 'str'>
So, I want to get bin() function return as an integer
The int function is used to convert to the integer. We need to pass the number and its base to convert it into an integer (since, the base for binary values is 2).
a = int('101',2)
print(a)
If you question is about converting for example 5 into bin in python, the bin function actually gives 0b101 as the result. So the simple trick to get 101 as an int is 👇
intnum=int(bin(number)[2:])
This question already has answers here:
Given n, take tsum of the digits of n. If that value has more than one digit, continue reducing a single-digit number is produced
(4 answers)
Closed 1 year ago.
I have problem and trying to get next:
new_string = "35" #and this result must be like new_int = 3+5.
How im available to do this? I know the type conversion, but not a clue how i should do this.
As you are new to the python, i suggest you doing it using
int(new_string[0]) # 3
int(new_string[1]) # 5
So now you have 2 integers, you can to whatever you want
This question already has answers here:
How can I convert a string with dot and comma into a float in Python
(9 answers)
Closed 4 years ago.
my question is simple.
I got my string :
a = '0,0127'
I want to convert it to a number but when i compile
float(a)
i got the following message error :
ValueError: could not convert string to float: '0,0127'
Is there another way to convert it to a number ?
Using str.replace
Ex:
a = '0,0127'
print(float(a.replace(",", ".")))
Output:
0.0127
The reason this isn't working is because the decimal type only recognizes periods (.) for the decimal delimiter as this is what is common in, e.g., english. You could manually change the string or do
a = a.replace(",", ".")
float(a)
Which should work.
This question already has answers here:
Keep % format of float values
(3 answers)
Closed 4 years ago.
I initially had the columns below in string, and I converted them into float for some calculation purposes.
Growth1 Growth2
4,365.46% 124.48%
45.29% 2.222222222222%
251.48% 23.999999999999%
df[['Growth1', 'Growth2']] = df[['Growth1', 'Growth2']].replace('%|,', '', regex=True).astype(float, errors='ignore')/100
Growth1 Growth2
43.6546 1.2448
0.4529 0.02222222222222
2.5148 0.23999999999999
However, they are in decimal format and I want them to show in % format. But I can't just add {:,.2%}'.format after a line like:
df[['Growth1', 'Growth2']] = df[['Growth1', 'Growth2']].replace('%|,', '', regex=True).astype(float, errors='ignore')/100(formatters=[{:,.2%}'.format])
Is there any way that you can do to keep the float in % format and round it to the 2 decimal places with the least amount of code (like 1 or 2 lines)? Thank you.
Desired output:
Growth1 Growth2
4,365.46% 124.48%
45.29% 2.22%
251.48% 24.00% # or 23.99%, no big deal
It looks like the parameter you use for format is not correct. It should be {:,.2f}, and % outside:
Example:
>>> "{:,.2f}%".format(4365.46)
'4,365.46%'
Maybe using pandas style?
df.style.format("{:.2%}")
When you display the returned object from this call, like you normally would a dataframe, it'll have your columns formatted in the manner you've requested.
df['Growth1'] = pd.Series(['{0:.2f}%'.format(val * 100) for val in df['Growth1']], index = df.index)
The same for "Growth2" column.
Note: if you want to keep the original column, just name the new one something other than "Growth1"