Fundamentals 11 min read

Python String Methods: Upper, Lower, Count, Strip, Split, Replace, Join, and More

This article introduces essential Python string methods—including upper(), lower(), count(), strip(), lstrip(), rstrip(), split(), join(), replace(), isdigit(), isspace(), startswith(), and endswith()—explaining their use cases with clear examples and code snippets for effective text processing.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python String Methods: Upper, Lower, Count, Strip, Split, Replace, Join, and More

Introduction

Strings are a fundamental data type in Python and play an indispensable role in data processing. Mastering common string methods can greatly improve efficiency in tasks such as comparison, counting, cleaning, and transformation.

1. Uppercase and Lowercase Methods

The upper() method converts a string to all uppercase characters, while lower() converts it to all lowercase characters. Converting to a uniform case is often necessary before performing comparisons or statistical analysis, especially with English text.

For example, to handle user input that may be either "n" or "N", you can use lower() (or upper() ) to normalize the input before the comparison:

<code>choice = input('是否继续执行程序,输入n或N则结束:')
if choice == 'n' or choice == 'N':
    print('程序结束')
# Recommended approach
if choice.lower() == 'n':
    print('程序结束')</code>

When counting occurrences of a word in a list of tokens, it is also advisable to lowercase the strings first:

<code>words = ['When', 'you', 'fall', 'stand', 'up.', 'And', 'when', 'you', 'break', 'stand', 'tough', 'And', 'when', 'they', 'say', 'you', "can't,", 'you', 'say', 'I', 'can', 'I', 'can']
count = 0
sta_word = 'when'
for word in words:
    if word.lower() == sta_word:
        count += 1
print('{}出现了{}次'.format('when', count))  # Output: when出现了3次</code>

2. Counting Occurrences

The count() method quickly returns the number of times a substring appears in a string. Although more commonly used with lists, it can be applied to strings as well; misuse may lead to subtle bugs.

Example with Chinese text shows that count() works on raw strings, but for accurate word‑frequency analysis you often need to tokenize first (e.g., using jieba ) and then apply count() on the token list.

<code>"帽子和服装如何搭配才好看".count("和服")  # Returns 1
import jieba
words = jieba.lcut("帽子和服装如何搭配才好看")
words.count("和服")  # Returns 0 because tokenization splits the phrase</code>

3. Stripping Characters

When cleaning noisy data, strip() , lstrip() , and rstrip() remove unwanted characters from the beginning and/or end of a string. Without arguments they remove whitespace; with a character set they remove any of those characters.

<code>temp_str = "  tomorrow is another day "
print(temp_str.strip())  # 'tomorrow is another day'
temp_str = "#  tomorrow is another day @"
print(temp_str.strip('#'))          # '  tomorrow is another day @'
print(temp_str.strip('# @'))        # 'tomorrow is another day'
temp_str = "#@  tomorrow is another day @"
print(temp_str.lstrip('@# '))       # 'tomorrow is another day @'</code>

4. Splitting Strings

The split() method divides a string into a list using a specified delimiter (default is whitespace). It is useful for extracting fields from structured text such as CSV or JSON‑like strings.

<code>temp_str = "Whatever is worth doing is worth doing well"
print(temp_str.split())
# ['Whatever', 'is', 'worth', 'doing', 'is', 'worth', 'doing', 'well']

temp_str = "tomorrow#is#another#day"
print(temp_str.split('#'))
# ['tomorrow', 'is', 'another', 'day']

temp_str = '"name":"Mike","age":18,"sex":"male","hair":"black"'
print(temp_str.split(','))
# ['"name":"Mike"', '"age":18', '"sex":"male"', '"hair":"black"']</code>

5. Replacing Substrings

The replace() method substitutes occurrences of a substring with another string. An optional third argument limits the number of replacements.

<code>temp_str = "this is really interesting, and that is boring."
print(temp_str.replace('is', 'was'))
# 'thwas was really interesting, and that was boring.'

temp_str = "I really really really like you."
print(temp_str.replace('really', '', 2))
# 'I   really like you.'</code>

Be careful when replacing short patterns like "is" because they may appear inside other words; adding surrounding spaces can avoid unintended changes.

6. Joining Strings

The join() method concatenates an iterable of strings using a specified separator, effectively the inverse of split() .

<code>seq = 'hello world'
print(':'.join(seq))
# 'h:e:l:l:o: :w:o:r:l:d'

seq = ('Whatever', 'is', 'worth', 'doing', 'is', 'worth', 'doing', 'well')
print('*'.join(seq))
# 'Whatever*is*worth*doing*is*worth*doing*well'

seq = ['"name":"Mike"', '"age":18', '"sex":"male"', '"hair":"black"']
print('#'.join(seq))
# '"name":"Mike"#"age":18#"sex":"male"#"hair":"black"'</code>

7. Checking for Digits

The isdigit() method returns True if all characters in the string are digits; it returns False for strings containing decimal points, signs, or other characters.

<code>num = "13579"
print(num.isdigit())  # True
num = "1.0"
print(num.isdigit())  # False
num = "-1"
print(num.isdigit())  # False</code>

8. Checking for Whitespace

The isspace() method returns True if the string consists solely of whitespace characters; an empty string returns False .

<code>t = ''
print(t.isspace())  # False
t = '  '
print(t.isspace())  # True</code>

9. Checking Prefixes and Suffixes

The startswith() and endswith() methods test whether a string begins or ends with a given substring, optionally within a slice defined by start and end indices.

<code>temp_str = "Whatever is worth doing is worth doing well"
print(temp_str.startswith('W'))          # True
print(temp_str.startswith('What'))       # True
print(temp_str.startswith('Whatever', 2))  # False
print(temp_str.endswith('well', 2))      # True
print(temp_str.endswith('we', 2, -2))   # True</code>

Promotional Notice (Non‑Academic)

The original source concludes with a QR‑code and links promoting a free Python public course and related learning materials. This part is promotional and not part of the technical tutorial.

pythonprogrammingTutorialtext processingstring methods
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login 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.