Categories
Python Answers

How to check for palindromes using Python?

Sometimes, we want to check for palindromes using Python.

In this article, we’ll look at how to check for palindromes using Python.

How to check for palindromes using Python?

To check for palindromes using Python, we can use the Python slice syntax.

For instance, we write:

def is_palindrome(n):
    return str(n) == str(n)[::-1]


print(is_palindrome('abba'))
print(is_palindrome('foobar'))

to create the is_palindrome function that takes a string n and check if the string is the same as is and when it’s reversed.

We reversed n with str(n)[::-1].

Therefore, print should print:

True
False

respectively.

Conclusion

To check for palindromes using Python, we can use the Python slice syntax.

Categories
Python Answers

How to remove punctuation with Python Pandas?

Sometimes, we want to remove punctuation with Python Pandas.

In this article, we’ll look at how to remove punctuation with Python Pandas.

How to remove punctuation with Python Pandas?

To remove punctuation with Python Pandas, we can use the DataFrame’s str.replace method.

For instance, we write:

import pandas as pd

df = pd.DataFrame({'text': ['a..b?!??', '%hgh&12', 'abc123!!!', '$$$1234']})
df['text'] = df['text'].str.replace(r'[^\w\s]+', '')

print(df)

We call replace with a regex string that matches all punctuation characters and replace them with empty strings.

Therefore, df is:

import pandas as pd

df = pd.DataFrame({'text': ['a..b?!??', '%hgh&12', 'abc123!!!', '$$$1234']})
df['text'] = df['text'].str.replace(r'[^\w\s]+', '')

print(df)

replace returns a new DataFrame column and we assign that to df['text'].

Therefore, df is:

     text
0      ab
1   hgh12
2  abc123
3    1234

Conclusion

To remove punctuation with Python Pandas, we can use the DataFrame’s str.replace method.

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.