How to extract significant numeric digits from an alphanumeric string? - python

I have an ID DIS002789.I want to extract 2789 from the given ID.I have to use the extracted number in a for loop using a variable.
I tried using re.findall.
inputk='DIS0002789'
non_decimal = re.findall(r'[\d.]+', inputk)
for n in range(non_decimal, non_decimal + 1000):
Im getting 002789. But I want my output to be 2789.And also i cant use the for loop because of this.It shows a n error saying 002789 is an invalid syntax.
I tried converting it to int. but its shows the following error,
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

you can pass the result of re.findall(r'[\d.]+', inputk) to int in order to make it an integer. int('0123') will ignore leading zeroes.
Example:
inputk='DIS0002789'
non_decimal = int(re.findall(r'[\d.]+', inputk))
if you want it to be a string you can pass it to str again: str(int('0123')) == '123'

If you want the int value, you should convert it to integer as other answers show. If you only want the string, you can try adding the optional leading zeros:
inputk='DIS0002789'
non_decimal = re.findall(r':?[0]*(\d+)', inputk)
non_decimal
output:
['2789']

you can ignore leading zeros and convert it to an integer to use in a loop
inputk='DIS0002789'
non_decimal = int(re.findall(r':?[0]*(\d+)', inputk)[0])

Related

How to convert a single char in a sliced String into Integer in Python?

For example, I have a
String = "TGR1UK"
I only need the number 1 in the string to do some math operation so I make a number variable as
number = String[3]
but the type of this "number" is actually Char
and I cant use
number = (int)String[3]
to cast it into an integer
what should I do?
number = int(String[3])
This will cast it to an int. Read more here:
https://careerkarma.com/blog/python-string-to-int/
Edit:
I have assumed when you said:
but the type of this "number" is actually Char and I cant use
number = (int)String[3]
That you meant that wasnt working, because that is not how you cast to an int in python. Did you mean you aren't allowed to use a straight cast for some reason?
You're using int wrong. int is used as follows:
int(string)
So, try number = int(String[3]).

How to convert from float to int to string? invalid literal for int() with base 10: 'x'

how convert float to int to string?
with open(DATA_DIR+'/test.csv', 'r') as inp:
reader = csv.DictReader(inp, delimiter=',',fieldnames = ['Id', 'Target'])
for row in csv.reader(inp):
text_file.write("Text "+str(int(row[1])))
Error: ValueError: invalid literal for int() with base 10: '323.0'
EDIT: The CSV parser is already reading the data that you are trying to convert as a string. That string has decimal point values which it won't convert to int. It will convert it to float though.
Here are 2 ways to do this:
Just split the string and use the integral part
in your example do text_file.write('Text {:.0f}'.format(float(row[1]))
With the 2nd approach you are basically converting it to float and thereafter you don't care for anything on the right of the decimal. So .0f indicates you don't want anything after the decimal including the .. More on this formatting can be learned in the link I pasted below.
As you dig deeper you should continue to use type() to identify the incoming data before you decide what to do with it.
ORIGINAL PART:
You don't have to convert the data to achieve what you want. At the end of it you want to write to a file as a string. If what you are getting from the csv is a float then you could simply format your string as
write_line = 'Text {:06.2f}'.format(row[1])
text_file.write(write_line)
Of course you could condense the two lines.
There is more info in python's docs - https://docs.python.org/3/tutorial/inputoutput.html
x=Decimal(row[1]).normalize()
text_file.write(x)
Probably looks like row[1] is not having any numeric value. Can u specify what exactly it will hold?
Try printing row[i] before executing the int() function and see what value it is holding.

Keep zero digit save while converting string to integer in python

I am converting a string into integer using int function and it is working fine but i want to keep save zero digit that are at the start of the string.
string_value = '0123'
print(int(string_value))
result is 123
How can i format output 0123 as in integer type value not in string.
You can't, but if you want to put 0's (zero padding) at the beginning of your number, this is the way to do it.
"{:04}".format(123)
# '0123'
"{:05}".format(123)
# '00123'
Like every one said you can try above answers or the following :
string_value = '0123'
int_no = int(string_value)
print("%04d" % int_no)
print(string_value.zfill(4))
Both will give same answer
Impossible, you cannot get an integer value of 0123.
You should change your mind, you do not actually need 0123 in integer, but you need to keep zero when displaying it. So the question should change to how to format output.

Why does Python remove leading zeroes when converting from string to int?

>>> num = int('0241034812')
>>> print(num)
241034812
>>>
In the above code, I'm setting the variable num to 0241034812; however, when I print the variable it deletes the first zero.
Why is this happening?
Integers are stored/displayed as a "normal" number, not the string value. If you want to display the number prefixed with zeroes you can do that when displaying the variable.
You can use the following syntax to add leading zeros to an integer:
print "%010d" % (241034812,)
The example above will display the integer 241034812 with 10 digits as 0241034812.
I'm setting the variable 'num' to '0241034812'
No, you're setting it to 241,034,812: an integer value, about two hundred forty million. If you want to set it to '0241034812', you should use a string rather than an integer. That is, you should drop the call to int:
>>> num = '0241034812'
>>> print(num)
0241034812
>>>
If you're storing some number in a format where a leading zero would be useful/significant (maybe a barcode, ISBN, or the like), you can re-add them when converting back into a string using .format
>>> num = int('0241034812')
>>> print('{:010d}'.format(num))
0241034812
Briefly, the first 0 in the format spec means to add leading zeros if not present to fill 10 (the 10) characters.
You wanted to print your integer to a specific zero-padded width, use string formatting. The format() function, for example:
>>> num = 241034812
>>> print(format(num, '010d'))
0241034812
or print the original string from which you parsed the integer in the first place.
Integers do not store a 'print width' or any number of leading 0 digits.

Converting string to integer with python

When trying to convert a string into integer to be used as a variable later in the code, I get the following:
print int(urlsuccessful[i])
ValueError: invalid literal for int() with base 10: '2,919,247'
locale.atoi() will "demark" integers based on the current locale setting.
If only problems are commas, try:
>>> int("2,919,247".replace(",", ""))
2919247
int does not understand commas, you'll want to remove those before trying to convert
You can just do
def int2str(my_integer):
return "%d" % my_integer

Categories

Resources