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.
1. Get string length and count occurrences
str1 = "我的电脑有点卡了,你的电脑卡吗?"
print(len(str1)) # 16
print(str1.count("电脑")) # 2The 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 MuchThese 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.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
