theprowler theprowler -4 years ago 34
Python Question

Turn number inside a list to number outside a list; a string

I extracted just a number from a string with:

weight = [int(s) for s in fish.split() if s.isdigit()]
, the result is a
list
:
[7088]


I try to turn that list into a string by doing:

weight = str(weight)
print("weight:", weight)
but the printout remains:

weight: [7088]


So I tried returning just an integer with:

weight = int(weight)
but got:

ValueError: invalid literal for int() with base 10: '[7088]'


So instead I tried converting the initial list number to a float with:

weight = float(weight)
but got:

ValueError: could not convert string to float: '[7088]'


Ultimately this causes my code to fail because my RegEx doesn't recognize that as a number. (RegEx:
regnumber = re.compile(r"(\d),(\d) | (\d)")
)

Is there a simple way to turn the initial returned number inside of a list into a number/string/integer than my RegEx can actually recognize?

Answer Source

If it is just one number in the list always, you can do:

weight = str(weight[0])

or use float(), int(), etc, based on your requirement

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download