10个Python字符串函数,让你的字符串操作更简单!
发布时间:2023-06-06 15:25:10
1. split()函数
这个函数用来分离字符串。假如你有一个以空格分隔的字符串,你可以使用split()函数将其分离成一个单独的字符串列表:
sentence = "I am learning Python" words = sentence.split() print(words) # ['I', 'am', 'learning', 'Python']
2. join()函数
join()函数与split()函数相反,它用来将列表、元组、字典等数据结构中的字符串连接起来:
words = ['I', 'am', 'learning', 'Python'] sentence = " ".join(words) print(sentence) # I am learning Python
3. strip()函数
strip()函数用来去除字符串开头和结尾的空格或指定的字符:
string = " Python "
print(string.strip()) # Python
print(string.strip('P')) # Python
4. replace()函数
这个函数用来替换字符串中的指定文本:
string = "I love Python"
new_string = string.replace("Python", "programming")
print(new_string) # I love programming
5. lower()函数
这个函数用来将字符串转换为小写:
string = "I LOVE PYTHON" print(string.lower()) # i love python
6. upper()函数
这个函数用来将字符串转换为大写:
string = "i love python" print(string.upper()) # I LOVE PYTHON
7. find()函数
这个函数用来查找字符串中某个子串的位置:
string = "Python is a great language"
print(string.find("great")) # 13
8. startswith()函数和endswith()函数
这两个函数用来检查字符串是否以指定的前缀或后缀开头或结尾:
string = "Python is a great language"
print(string.startswith("Python")) # True
print(string.endswith("language")) # True
9. isdigit()函数
这个函数用来检查字符串是否只包含数字字符:
string1 = "12345" print(string1.isdigit()) # True string2 = "1234x" print(string2.isdigit()) # False
10. splitlines()函数
这个函数用来将字符串按行分隔成一个字符串列表:
string = "Python is a great language" lines = string.splitlines() print(lines) # ['Python', 'is', 'a', 'great', 'language']
总结
这里介绍的是一些常用的Python字符串函数,使用它们可以轻松地完成许多字符串操作。当然,Python还有很多其他的字符串函数,读者可以根据自己的需求来使用。
