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