Python中关于字符串的常用函数及应用方法
Python中的字符串是指由字符组成的序列,它是一种不可变类型。字符串和数字一样是Python中最常用的数据类型之一,因此Python提供了很多字符串操作函数,下面为大家简单介绍一些常用的字符串方法和用法。
1. 字符串长度:len函数
len()函数可以用来获取一个字符串的长度,例如:
s = "hello world" print(len(s))
输出结果为 11,因为 "hello world" 这个字符串包含了 11 个字符。
2. 查找字符串中的字符:find方法
find()方法可以用来查找一个字符或子字符串在给定字符串中第一次出现的位置,例如:
s = "hello world"
print(s.find('o')) # 查找字符 o,在 s 中第一次出现的位置
print(s.find('world')) # 查找子字符串 "world" 在 s 中第一次出现的位置
输出结果为2和6,分别表示字符 o 和子字符串 "world" 第一次出现的位置。如果查找不到,find()方法也会返回 -1。
3. 替换文本:replace方法
replace()方法可以用来替换字符串中的字符或子字符串,比如:
s = "hello world"
print(s.replace('o', 'a')) # 将 s 中的字符 o 替换为字符 a
print(s.replace('world', 'python')) # 将 s 中的子字符串 "world" 替换为 "python"
输出结果分别为 "hella warld" 和 "hello python"。
4. 分割字符串:split方法
split()方法可以用来分割字符串,例如:
s = "hello world"
print(s.split(' ')) # 以空格为分隔符分割 s,返回一个包含两个字符串的列表
输出结果为 ["hello", "world"]。
5. 大小写转换:upper和lower方法
upper()方法可以用来将字符串中的所有字母都转换为大写字母,而lower()方法可以将所有字母转换为小写字母,例如:
s = "Hello World" print(s.upper()) # 将 s 中的所有字母转换为大写字母 print(s.lower()) # 将 s 中的所有字母转换为小写字母
输出结果分别为 "HELLO WORLD" 和 "hello world"。
6. 判定开头和结尾:startswith和endswith方法
startswith()和endswith()方法可以用来判断字符串是否以特定的字符串开头或结尾,例如:
s = "hello world"
print(s.startswith('hello')) # 判断 s 是否以 "hello" 开头
print(s.endswith('world')) # 判断 s 是否以 "world" 结尾
输出结果分别为 True 和 True。
7. 移除空格:strip方法
strip()方法可以用来移除字符串两端的空格或指定的其它字符,例如:
s = " hello world "
print(s.strip()) # 移除 s 两端的空格
print(s.strip(' l')) # 移除 s 两端的空格和字母 l
输出结果分别为 "hello world" 和 "hello wor"。
8. 拼接字符串:join方法
join()方法可以用来将一个列表或者元组中的所有元素拼接成一个字符串,例如:
s = ['hello', 'world']
print('-'.join(s)) # 用 - 符号将列表 s 中的元素拼接成一个字符串
输出结果为 "hello-world"。
9. 字符串格式化:format方法
format()方法可以用来将变量插入到字符串中,例如:
name = "Tom"
age = 18
print("My name is {}, and I'm {} years old.".format(name, age))
输出结果为 "My name is Tom, and I'm 18 years old."。
10. 其它方法
除了上述方法外,Python还提供了许多其它处理字符串的方法,比如:
* count()方法用于统计字符串中一个字符或子字符串的出现次数。
* isalnum()方法用于判断字符串中是否只包含字母和数字。
* isdigit()方法用于判断字符串是否只包含数字。
* isalpha()方法用于判断字符串是否只包含字母。
* islower()方法用于判断字符串中的字母是否全部为小写。
* isupper()方法用于判断字符串中的字母是否全部为大写。
以上这些方法只是Python中处理字符串的冰山一角,更多的字符串操作函数和用法可以参考Python的官方文档或其它相关教程。
