字符串有许多用于常见任务的内置方法。这些方法返回新的字符串,并且不会改变原始字符串。
更改大小写的基本方法
text = "hello python"
print(text.upper()) # HELLO PYTHON
print(text.lower()) # hello python
print(text.title()) # Hello Python
print(text.capitalize()) # Hello python
删除空白字符
messy = " hello "
print(messy.strip()) # "hello"
print(messy.lstrip()) # "hello "
print(messy.rstrip()) # " hello"
查找和替换
sentence = "I like cats and cats like me"
print(sentence.find("cats")) # 7 (first position)
print(sentence.replace("cats", "dogs")) # I like dogs and dogs like me
检查内容
email = "user@example.com"
print(email.startswith("user")) # True
print(email.endswith(".com")) # True
print("123".isdigit()) # True
print("abc".isalpha()) # True
分割和合并
words = "apple,banana,cherry"
word_list = words.split(",")
print(word_list) # ['apple', 'banana', 'cherry']
new_string = "-".join(word_list)
print(new_string) # apple-banana-cherry
简单示例
清理用户输入:
name = " Alice "
clean_name = name.strip().title()
print(clean_name) # Alice
计数出现次数(使用count方法)
text = "hello hello world"
print(text.count("hello")) # 2
快速摘要
- 用于格式化的方法,如
.upper()、.lower()、.strip()。 -
.find()、.replace()用于搜索和更改。 -
.startswith().endswith(),.isdigit()用于检查。 -
.split()和.join()对于列表和字符串。
在文本上练习常见的字符串方法。它们对于在 Python 程序中清理和处理字符串至关重要。





















