blog/docs/code/python/string-func.md

146 lines
2.4 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: String字符串的内建函数
date: 2020-07-21 22:27:31
tags: [Python]
categories: [Python]
author: Anges黎梦
---
## String的内建函数
`示例字符串`
```
var = " abcdefghijklmn黎梦 "
```
### capitalize()
> 将字符串的第一个字母转换为大写
```
print(var.capitalize())
```
### count()
> 统计字符串中某一个字符出现的次数,
```
print(var.count("b"))
print(var.count("b"[0:7])) # 在index范围内查找某一个字符出现的次数
```
### endswith()
> 是判断字符串是否以xxx结束返回布尔值
```
print(var.endswith("n"))
```
### find()
> 检测字符串是否包含某个字符若是则返回index若不是则返回-1
```
print(var.find('g'))
```
### index()
> 返回字符在字符串中的index值若不存在字符串中则抛出异常
```
print(var.index('c'))
```
### isalnum()
> 如果字符串至少有一个字符并且所有字符都是字母或者数字则返回True否则返回False
```
print(var.isalnum())
```
### isalpha()
> 如果字符串至少有一个字符并且所有字符都是字母或者中文字则返回True
```
print(var.isalpha())
```
### isdigit()
> 判断字符串是否只包含数字
```
print(var.isdigit())
```
### islower()
> 判断字符串中包含至少一个区分大小写的字符并且这些字符都是小写则返回True
```
print(var.islower())
```
### isupper()
> 判断字符串中包含至少一个区分大小写的字符并且这些字符都是大写则返回True
```
print(var.isupper())
```
### lower()
> 转换字符串所有字符为小写
```
print(var.lower())
```
### swapcase()
> 转换字符串所有字符 小写转换为大写,大写转换为小写
```
print(var.swapcase())
```
### upper()
> 转换字符串所有字符为大写
```
print(var.upper())
```
### len()
> 长度
```
print(len(var))
```
### join
```
print(",".join(["a","b","ccc"]))
```
### replace
```
print(var.replace("a", "Q"))
```
### lstrip()
> 清除左边的空格或者指定字符
```
print(var.lstrip())
```
### rstrip()
> 清除右边的空格或者指定字符
```
print(var.rstrip())
```
### split()
> 截取,分割
```
print(var.split("j"))
```
### startswith()
> 是否以xxx开头
```
print(var.startswith(' '))
```
### 字符串翻转
```
print(var[::-1])
print(reversed(var))
print(''.join(reversed(var)))
```
### sorted()
> 字符串排序
```
print(sorted(var))
```