Fundamentals 4 min read

Python String Basics: Finding Substrings and Getting Length

This tutorial demonstrates how to use Python's built-in string functions to obtain a string's length, count occurrences of a substring, convert case, and locate substrings using find, index, and rfind, with concrete code examples and expected outputs.

Lisa Notes
Lisa Notes
Lisa Notes
Python String Basics: Finding Substrings and Getting Length

1. Get string length and count occurrences

str1 = "我的电脑有点卡了,你的电脑卡吗?"
print(len(str1))          # 16
print(str1.count("电脑")) # 2

The length of str1 is 16 characters, and the substring "电脑" appears twice.

2. Convert string case

str2 = " i Miss you VERY much"
print(str2.upper())   # I MISS YOU VERY MUCH
print(str2.lower())   # i miss you very much
print(str2.swapcase())# I miSS TOU very MUCH
print(str2.title())   # I Miss You Very Much

These calls illustrate upper(), lower(), swapcase(), and title() transformations.

3. Find substring positions

str3 = "abcdefghijklmn123987654zxyslt"
print(str3.find("l"))        # 11
print(str3.find("o"))        # -1
print(str3.index("a"))       # 0
# print(str3.index("p")) would raise ValueError
print(str3.rfind("l"))       # 28
print(str3.rfind("q"))       # -1
print(str3.find("l", 3, 12)) # 11
print(str3.index("l", 3, 12))# 11
find()

returns the first index or -1 if not found, index() behaves similarly but raises an error when the substring is absent, and rfind() returns the last occurrence. The optional start and end arguments limit the search range.

Pythonstringlenfindcase-conversion
Lisa Notes
Written by

Lisa Notes

Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.