How to Count the Number of Distinct Letters in a String Using Python?

Estimated read time 2 min read

To count the number of distinct letters (i.e., the number of unique letters) in a string using Python, you can use a combination of the built-in set() function and the len() function.

Here’s an example:

# create a sample string
my_string = 'hello world'

# convert the string to a set of unique characters
unique_chars = set(my_string)

# count the number of unique characters
num_unique_chars = len(unique_chars)

print(f'The string "{my_string}" contains {num_unique_chars} distinct letters.')

In this example, we create a sample string ('hello world') and convert it to a set of unique characters using the set() function. We then use the len() function to count the number of unique characters in the set.

Finally, we print a message to the console indicating the number of distinct letters in the original string. The output will be:

The string "hello world" contains 9 distinct letters.

Note that this approach treats upper- and lower-case letters as distinct. If you want to ignore case, you can convert the string to lowercase (or uppercase) before creating the set of unique characters. For example:

# create a sample string
my_string = 'Hello World'

# convert the string to lowercase and then to a set of unique characters
unique_chars = set(my_string.lower())

# count the number of unique characters
num_unique_chars = len(unique_chars)

print(f'The string "{my_string}" contains {num_unique_chars} distinct letters.')

In this modified example, we first convert the original string to lowercase using the lower() method before creating the set of unique characters. This ensures that upper- and lower-case letters are treated as equivalent. The output will be:

The string "Hello World" contains 8 distinct letters.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply