使用Python内建函数操作字符串
Python是一种强大的编程语言,自带许多内建函数,可以用来操作和处理字符串。在日常开发中,字符串处理是一个很常见的需求,因此熟练使用Python内建函数处理字符串是非常有用的。本文将介绍一些常用的Python内建函数,帮助您更好地操作字符串。
1. len()
len()函数可以返回字符串的长度,即字符串中字符的个数。这个函数在字符串处理中非常常用。
示例代码:
str1 = "hello world" print(len(str1)) # 输出:11
2. capitalize()
capitalize()函数可以将字符串的 个字符变成大写字母,其他字符变成小写字母。
示例代码:
str2 = "hello world" print(str2.capitalize()) # 输出:Hello world
3. lower()
lower()函数可以将字符串中的所有字符都转化为小写字母。
示例代码:
str3 = "HelLo WORld" print(str3.lower()) # 输出:hello world
4. upper()
upper()函数可以将字符串中的所有字符都转化为大写字母。
示例代码:
str4 = "HelLo WORld" print(str4.upper()) # 输出:HELLO WORLD
5. strip()
strip()函数可以去掉字符串首尾的空格。
示例代码:
str5 = " hello world " print(str5.strip()) # 输出:hello world
6. replace()
replace()函数可以将字符串中的某个子串替换成另一个子串。
示例代码:
str6 = "hello world"
print(str6.replace("world", "universe")) # 输出:hello universe
7. split()
split()函数可以将字符串按照指定的分隔符分割成多个子串,并返回一个子串列表。
示例代码:
str7 = "hello,world,python"
print(str7.split(",")) # 输出:['hello', 'world', 'python']
8. join()
join()函数可以将一个字符串列表连接起来,形成一个新的字符串。
示例代码:
str8 = ["hello", "world", "python"]
print("-".join(str8)) # 输出:hello-world-python
9. isdigit()
isdigit()函数可以判断字符串是否只包含数字。
示例代码:
str9 = "123456" print(str9.isdigit()) # 输出:True
10. isalpha()
isalpha()函数可以判断字符串是否只包含字母。
示例代码:
str10 = "hello" print(str10.isalpha()) # 输出:True
11. isalnum()
isalnum()函数可以判断字符串是否只包含字母和数字。
示例代码:
str11 = "hello123" print(str11.isalnum()) # 输出:True
12. startswith()
startswith()函数可以判断字符串是否以指定的子串开头。
示例代码:
str12 = "hello world"
print(str12.startswith("hello")) # 输出:True
13. endswith()
endswith()函数可以判断字符串是否以指定的子串结尾。
示例代码:
str13 = "hello world"
print(str13.endswith("world")) # 输出:True
14. find()
find()函数可以查找字符串中指定的子串,返回子串的起始位置。如果没有找到,则返回-1。
示例代码:
str14 = "hello world"
print(str14.find("world")) # 输出:6
15. index()
index()函数和find()函数的功能差不多,但是如果没有找到子串,则会抛出异常。
示例代码:
str15 = "hello world"
print(str15.index("world")) # 输出:6
以上是Python内建函数中常用的字符串操作函数,熟练使用这些函数可以帮助您更快速地完成字符串处理任务。当然,函数的使用也要考虑上下文和实际需求,根据实际情况灵活选择。
