当前位置: 移动技术网 > IT编程>脚本编程>Python > Python字符串内置函数

Python字符串内置函数

2020年07月03日  | 移动技术网IT编程  | 我要评论

1. capitalize(字符串第一个字符大写)
In [1]: str = 'hello'

In [2]: str.capitalize()
Out[2]: 'Hello'
2. center(width)(字符串居中,width填充空白)
In [3]: str.center(20)
Out[3]: '       hello        '

3. string.count(str, beg, end)(返回字符出现的次数)
In [4]: str = 'sdsadsdasda'

In [5]: str.count('a')
Out[5]: 3
4. encode decode(编码解码)
In [6]: str = 'hello'

In [7]: str.encode('utf-8').decode('utf-8')
Out[7]: 'hello'
5. string.endswith(obj, beg, end)(判断是否以obj结束)

str.startswith(判断是否以obj开始)
如果是,返回true;否则返回false

In [8]: str
Out[8]: 'hello'

In [9]: str.endswith('o')
Out[9]: True

In [10]: str.endswith('a')
Out[10]: False
6. string.find(str, beg, end)(检测str是否在string中)

在返回索引值(第一次出现),不在返回-1

In [13]: str
Out[13]: 'hello'

In [14]: str.find('a')
Out[14]: -1

In [15]: str.find('l')
Out[15]: 2

string.index(str, beg=0, end=len(string)):不在会报错

7. string.format()(格式化字符串)
In [16]: '{} {}'.format('hello', 'world')
Out[16]: 'hello world'
8. string.isalnum()(判断是否所有字符都为数字或数字)
In [19]: str
Out[19]: 'hello'

In [20]: str.isalnum()
Out[20]: True

In [21]: str = 'hello,'

In [22]: str.isalnum()
Out[22]: False
9. string.isalpha()(是否都为字母)
10. string.isdigit()(是否都为数字)
11. string.islower()(是否都为小写)
12. string.isnumeric()(如果 string 中只包含数字字符,则返回 True,否则返回 False)
13. str.casefold(大写转小写)
In [25]: str = 'HELLO'

In [26]: str.casefold
Out[26]: <function str.casefold()>

In [27]: str.casefold()
Out[27]: 'hello'

本文地址:https://blog.csdn.net/gklcsdn/article/details/107082307

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网