二、字符串方法
1. 获取字符串的长度,使用函数len()
1 a = "Hello, World!"
2 print(len(a))
2. 删除字符串前后空格,使用函数strip()
1 a = "Hello, World!"
2 print(a.strip())
说明: 如果只删除左边的空格,使用函数lstrip(); 如果只删除右边的空格,使用rstrip()
3. 返回大写的字符串,使用upper()
1 a = "Hello, World!"
2 print(a.upper())
4. 返回小写的字符串,使用lower()
1 a = "Hello, World!"
2 print(a.lower())
5. 用一个字符串,替换另一个字符串,使用函数replace()
1 a = "Hello, World!"
2 print(a.replace("World", "Kathy"))
6. 分割一个字符串,将字符串中的一个字符作为分隔符,使用函数split()
1 a = "Hello, World!"
2 print(a.split(","))
说明:这个函数返回的结果是列表
['Hello', ' World!']
7. 返回指定值在字符串中出现的次数,使用函数count()
1 txt = "I love apples, apple are my favorite fruit"
2 x = txt.count("apple")3 print(x)
8. 使用指定的编码对字符串进行编码,默认的编码为‘utf-8’。编码使用函数encode()
1 txt = "My name is Kathy."
2 x =txt.encode(encoding='ascii')3 print(x)
9. 函数string.starts(value, start, end), 判断字符串是否以给定值开始,可定义字符串从哪个位置开始判断,并哪个位置结束判断,后两个参数可省略。函数返回布尔值。
1 txt = "Hello, welcome to my world."
2 x = txt.startswith("Hello") #判断字符串txt是否以Hello开头
3 print(x)4
5 txt = "Hello, welcome to my world."
6 x = txt.startswith("wel", 7, 20) #判断字符串txt的第7个字符到20个字符是否以wel开头
7 print(x)
说明:这个方法相类似的还有 string.endswith() 判断字符串是否以给定值结尾
10. 函数string.find(value, start, end), 在字符串中搜索给定的值,返回首次出现的位置,如果找不到,则返回-1. 该方法和string.index()相似,只不过后者如果没有找到将发生异常。
1 txt = "Hello, welcome to my world."
2 x = txt.find("welcome")3 print(x)
11. 函数string.isalnum(),判断字符串是否都是字母数字,返回布尔值。类似的方法还有:isalpha(), isdecimal(), isdigit(), islower(), isupper(), isnumeric(), isidentifier(), isspace(),
1 txt = "Company12"
2 x =txt.isalnum()3 print(x)
参考资料:
http://python.org
https://www.w3school.com.cn
https://www.runoob.com