This question already has answers here:
Change a string of integers separated by spaces to a list of int
(8 answers)
Closed 1 year ago.
In textEdit there are numbers separated by line breaks and I want to use them, but these numbers are a string and I couldn't convert them to integers.
This error is shown
ValueError: invalid literal for int() with base 10:' 15\n300\n2000\n'.
How can I use this content of TextEdit as integers?
t = self.TextEdit_numbers.toPlainText()
numbers = int(t)
I see there is a new line (\n) symbol in your TextEdit_numbers value.
It is not possible to convert something as
15
300
2000
to single integer.
I believe you want pass array of integers to your pie method.
You should try something like that:
self.numbers_string = self.TextEdit_numbers.toPlainText()
self.t = [int(n) for n in self.numbers_string.split('\n')
pyplot.pie(self.t, normalize=True)
In second line I use list comprehensions, you can read more about it here (https://www.w3schools.com/python/python_lists_comprehension.asp), and standard python string .split() method, more info here: https://www.w3schools.com/python/ref_string_split.asp
If you have integers on each line, this would give you a list of all those integers:
with open('TextEdit_numbers.txt') as f:
numbers = [int(x) for x in f]
Assuming the txt file has inputs like:
15
200
3000
The output would be the array number as:
[15, 200, 3000]
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:
Taking multiple integers on the same line as input from the user in python
(19 answers)
Closed 1 year ago.
I want to take multiple integer inputs in the same line. I know I can take str input and then convert them into integer in the next line but is there any way I can do it in the same line.
I have tried this:
x,y = int(input("->")).split()
print(x,y)
I am getting this error :
ValueError: invalid literal for int() with base 10
You messed up with parenthesis (split works on string not int)
then you expect a tuple for x,y = ...
the solution is:
x, y = [int(i) for i in input("->").split()]
print(x, y)
You are taking int as input which cant be split
x,y = input("->").split()
print(x,y)
you can change to int if you like later
print(int(x),int(y))
This question already has answers here:
Regular expression to return text between parenthesis
(11 answers)
Closed 1 year ago.
I have a string where I need to keep two key numbers and remove the rest which need to be converted to a string that can be used to slice data.
sample = 'range(0, 286)range(300, 511)'
I will always need the first two numbers (ex. 0 and 286). Each of these numbers will not always be 0 and 286. They can have multiple positions like 10 and 1000 or 100 and 10000. They will always be in parentheses and have a comma to separate each number. The second set of numbers do not need to be extracted from the string.
Expected Output: My end product would be a string that looks like a slice:
print([sample])
[0:286]
How do I extract just the first two numbers from this text, zero and two-hundred-eighty-six?
Assuming the following input:
series = pd.Series(['range(0, 286)range(300, 511)', 'range(100, 1000)range(300, 511)'])
you can use str.extract with named groups:
series.str.extract('range\((?P<number1>\d+),\s+(?P<number2>\d+)\)')
output:
number1 number2
0 0 286
1 100 1000
This question already has answers here:
How do I pad a string with zeroes?
(19 answers)
Closed 3 years ago.
I'm trying to make length = 001 in Python 3 but whenever I try to print it out it truncates the value without the leading zeros (length = 1). How would I stop this happening without having to cast length to a string before printing it out?
Make use of the zfill() helper method to left-pad any string, integer or float with zeros; it's valid for both Python 2.x and Python 3.x.
It important to note that Python 2 is no longer supported.
Sample usage:
print(str(1).zfill(3))
# Expected output: 001
Description:
When applied to a value, zfill() returns a value left-padded with zeros when the length of the initial string value less than that of the applied width value, otherwise, the initial string value as is.
Syntax:
str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.
Since python 3.6 you can use fstring :
>>> length = 1
>>> print(f'length = {length:03}')
length = 001
There are many ways to achieve this but the easiest way in Python 3.6+, in my opinion, is this:
print(f"{1:03}")
Python integers don't have an inherent length or number of significant digits. If you want them to print a specific way, you need to convert them to a string. There are several ways you can do so that let you specify things like padding characters and minimum lengths.
To pad with zeros to a minimum of three characters, try:
length = 1
print(format(length, '03'))
I suggest this ugly method but it works:
length = 1
lenghtafterpadding = 3
newlength = '0' * (lenghtafterpadding - len(str(length))) + str(length)
I came here to find a lighter solution than this one!
This question already has answers here:
Convert number strings with commas in pandas DataFrame to float
(4 answers)
Closed 7 years ago.
Here's my problem: I have a column of numbers in pandas.dataFrame. But there are certain numbers that need to be converted because they might be string's.
Here's how the column currently looks:
[1
-1,650.00
-3
...]
I want it all to be integers. My code was:
df['columnname'].astype(int)
However, when I convert -1,650.00 to integer I'm getting an error. Even when the code is
df['columnname'].astype(float)
df['columnname'].astype(int)
It still doesn't solve the problem. It says could not convert string to float: - and the "-" is still not handled.
Try this:
df['columnname'].replace(',','').astype(float)
Or:
float(df['columnname'].replace(',',''))
Float numbers use a dot to separate the integral part from the decimal part, not commas. Your vector should look something like this:
[1,
-1650.00,
-3,
]