Software engineering and personal development

Tag: string (Page 1 of 2)

Simplify Frequency Counting with Python’s collections.Counter

In the vast landscape of Python’s standard library, there’s a hidden gem that can significantly simplify the task of counting occurrences within an iterable. Say hello to the collections.Counter class, a versatile tool that effortlessly tallies the frequency of elements in your data. In this brief blog article, we’ll take a closer look at how you can harness the power of collections.Counter to elegantly count the occurrences of characters in a string.

Continue reading

Unveiling the Immutable Nature of Strings in Python

Strings are a fundamental data type in Python, forming the building blocks for text manipulation and processing. However, it’s crucial to understand that strings in Python are immutable. This means that once a string is created, it cannot be modified in-place. Attempting to directly modify a string will result in the creation of a new string object. In this article, we’ll explore the concept of string immutability, shed light on its implications, and emphasize the importance of utilizing appropriate string manipulation methods.

Continue reading

How to Quickly Capitalize First Letters in Python

One of the essential features of any programming language is the ability to manipulate strings. In this article, we’ll explore a simple yet powerful Python string method called title(). We will see how to use this method to capitalize the first letter of each word in a given string.

The title() method is a built-in Python string method that capitalizes the first letter of each word in a given string. It returns a new string where the first letter of each word is capitalized, and all other letters are in lowercase. Here is the syntax of the title() method:

string.title()
Continue reading

How to Perform Math Operations Inside Strings in Python

In Python, it’s possible to perform mathematical operations inside of string literals, using a feature called “f-strings”. F-strings, or “formatted string literals”, allow you to embed expressions inside string literals, which are evaluated at runtime. This allows you to mix variables, arithmetic expressions, and other computations into strings in a very readable and convenient way.

num_val = 42

print(f'{num_val % 2 = }') # num_val % 2 = 0

Here, the f-string '{num_val % 2 = }' is a string literal that contains an expression num_val % 2. The % operator is used to perform the modulo operation, which returns the remainder of the division of one number by another. In this case, num_val % 2 returns the remainder of the division of 42 by 2, which is 0.

Continue reading

How to Quickly Check if 2 Strings Are Anagrams using Counter

Anagrams are strings that have the same letters but in a different order for example abc, bca, cab, acb, bac are all anagrams, since they all contain the same letters.

We can check whether two strings are anagrams in Python in different ways. One way to do that would be to use Counter from the collections module.

From the documentation:

 A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

In plain English, with Counter, we can get a dictionary that represents the frequency of elements in a list. Let us see this in an example:

 from collections import Counter
 ​
 print(Counter("Hello"))  # Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})

Now we can use Counter to quickly check whether two strings are anagrams or not:

 from collections import Counter
 ​
 ​
 def check_if_anagram(first_string, second_string):
     first_string = first_string.lower()
     second_string = second_string.lower()
     return Counter(first_string) == Counter(second_string)
 ​
 ​
 print(check_if_anagram('testinG', 'Testing'))  # True
 print(check_if_anagram('Here', 'Rehe'))  # True
 print(check_if_anagram('Know', 'Now'))  # False

We can also check whether 2 strings are anagrams using sorted():

 def check_if_anagram(first_word, second_word):
     first_word = first_word.lower()
     second_word = second_word.lower()
     return sorted(first_word) == sorted(second_word)
 ​
 print(check_if_anagram("testinG", "Testing"))  # True
 print(check_if_anagram("Here", "Rehe"))  # True
 print(check_if_anagram("Know", "Now"))  # False

That’s basically it.

I hope you find this useful.

« Older posts

© 2024 Fatos Morina

Theme by Anders NorenUp ↑