Categories
Python Answers

How to check if a string can be converted to float in Python?

Sometimes, we want to check if a string can be converted to float in Python.

In this article, we’ll look at how to check if a string can be converted to float in Python.

How to check if a string can be converted to float in Python?

To check if a string can be converted to float in Python, we can wrap the float function call with a try-except block.

For instance, we write:

val = 'foobar'
try:
    float(val)
except ValueError:
    print("Not a float")

We call float with val to try to parse the string into a float.

This will raise a ValueError exception since 'foobar' isn’t a string with a floating point number.

Therefore, 'Not a float' is printed since it’s caught by the except block.

Conclusion

To check if a string can be converted to float in Python, we can wrap the float function call with a try-except block.

Categories
Python Answers

How to profile memory usage in Python?

Sometimes, we want to profile memory usage in Python.

In this article, we’ll look at how to profile memory usage in Python.

How to profile memory usage in Python?

To profile memory usage in Python, we can use the guppy module.

For instance, we write:

from guppy import hpy

h = hpy()
heap = h.heap()
print(heap)

We call hpy to return an object with the heap method.

heap returns a string with the memory usage data in a string.

Therefore, heap is something like:

Partition of a set of 35781 objects. Total size = 4143541 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0  10581  30   946824  23    946824  23 str
     1   7115  20   494688  12   1441512  35 tuple
     2   2534   7   447560  11   1889072  46 types.CodeType
     3   5001  14   354149   9   2243221  54 bytes
     4    449   1   349104   8   2592325  63 type
     5   2337   7   317832   8   2910157  70 function
     6    449   1   245120   6   3155277  76 dict of type
     7    101   0   179024   4   3334301  80 dict of module
     8    264   1   112296   3   3446597  83 dict (no owner)
     9   1101   3    79272   2   3525869  85 types.WrapperDescriptorType
<121 more rows. Type e.g. '_.more' to view.>

Size and cumulative are memory usage in bytes.

Conclusion

To profile memory usage in Python, we can use the guppy module.

Categories
Python Answers

How to read multiple lines of raw input with Python?

Sometimes, we want to read multiple lines of raw input with Python.

In this article, we’ll look at how to read multiple lines of raw input with Python.

How to read multiple lines of raw input with Python?

To read multiple lines of raw input with Python, we can use the iter function.

For instance, we write:

sentinel = 'x'
result = '\n'.join(iter(input, sentinel))
print(result)

to call iter with input and sentinel to read in input text until the sentinel string is entered and return a list with the inputted values in a list excluding the sentinel value.

And then we call join to join all the entered text with a new line.

Finally, we assign the list to results.

Conclusion

To read multiple lines of raw input with Python, we can use the iter function.

Categories
Python Answers

How to sort list in descending order with Python?

Sometimes, we want to sort list in descending order with Python.

In this article, we’ll look at how to sort list in descending order with Python.

How to sort list in descending order with Python?

To sort list in descending order with Python, we can use the sorted function with the reverse parameter set to True.

For instance, we write:

timestamps = [
    "2020-04-20 10:07:30", "2020-04-20 10:07:38", "2020-04-20 10:07:52",
    "2020-04-20 10:08:22", "2020-04-20 10:08:22", "2020-04-20 10:09:46",
    "2020-04-20 10:10:37", "2020-04-20 10:10:58", "2020-04-20 10:11:50",
    "2020-04-20 10:12:13", "2020-04-20 10:12:13", "2020-04-20 10:25:38"
]
s = sorted(timestamps, reverse=True)
print(s)

We call sorted with the timestamps list and reverse set to True to sort timestamps in reverse order and return the sorted list.

Therefore, s is:

['2020-04-20 10:25:38', '2020-04-20 10:12:13', '2020-04-20 10:12:13', '2020-04-20 10:11:50', '2020-04-20 10:10:58', '2020-04-20 10:10:37', '2020-04-20 10:09:46', '2020-04-20 10:08:22', '2020-04-20 10:08:22', '2020-04-20 10:07:52', '2020-04-20 10:07:38', '2020-04-20 10:07:30']

Conclusion

To sort list in descending order with Python, we can use the sorted function with the reverse parameter set to True.

Categories
Python Answers

How to create a dictionary from a CSV file?

Sometimes, we want to create a dictionary from a CSV file.

In this article, we’ll look at how to create a dictionary from a CSV file.

How to create a dictionary from a CSV file?

To create a dictionary from a CSV file, we can use the csv.DictReader class.

For instance, we write:

import csv

reader = csv.DictReader(open("foo.csv"))
for row in reader:
    print(row)

to read the foo.csv file with open.

Then we use the returned file as the argument for csv.DictReader to convert the rows to dictionaries.

Next, we loop through the reader iterator with a for loop.

In the loop body, we print the row value, which are dictionaries of each row.

If foo.csv is:

foo,bar
1,2
3,4
5,6

Then the for loop prints:

{'foo': '1', 'bar': '2'}
{'foo': '3', 'bar': '4'}
{'foo': '5', 'bar': '6'}

Conclusion

To create a dictionary from a CSV file, we can use the csv.DictReader class.