0
0
Pythonprogramming~5 mins

String length and membership test in Python

Choose your learning style9 modes available
Introduction

We use string length to know how many characters are in a word or sentence. Membership test helps us check if a letter or word is inside another word or sentence.

Checking if a password is long enough before accepting it.
Finding out if a message contains a certain word.
Counting how many letters are in a name.
Seeing if a letter is part of a word.
Syntax
Python
len(string)

substring in string

len(string) gives the number of characters in the string.

substring in string checks if substring is inside string and returns True or False.

Examples
This counts the letters in "hello" and gives 5.
Python
len("hello")  # returns 5
Checks if letter "a" is in the word "apple". It is, so it returns True.
Python
"a" in "apple"  # returns True
Checks if letter "z" is in "apple". It is not, so it returns False.
Python
"z" in "apple"  # returns False
Empty string has zero characters.
Python
len("")  # returns 0
Sample Program

This program counts letters in the word "banana" and checks if letters "a" and "z" are inside it.

Python
word = "banana"
print(f"The word '{word}' has {len(word)} letters.")

letter = "a"
if letter in word:
    print(f"The letter '{letter}' is in the word.")
else:
    print(f"The letter '{letter}' is not in the word.")

letter = "z"
if letter in word:
    print(f"The letter '{letter}' is in the word.")
else:
    print(f"The letter '{letter}' is not in the word.")
OutputSuccess
Important Notes

Spaces and punctuation count as characters in length.

Membership test is case sensitive: 'A' and 'a' are different.

Summary

Use len() to find how many characters are in a string.

Use in to check if a smaller string or letter is inside a bigger string.

These tools help us understand and check text easily.