1. 判断前缀后缀
In [1]: filename = "shellmad-zhangsan.pdf"
In [2]: filename.endswith(".pdf")
Out[2]: True
In [4]: filename.startswith("shellmad")
Out[4]: True
2. 判断是否是数字
In [1]: str1 = "12345"
In [2]: str2 = "hello"
In [3]: str1.isnumeric()
Out[3]: True
In [4]: str2.isnumeric()
Out[4]: False
3. 将字符串分割为list
我们可以使用字符串对象的split方法,通过指定的分隔符,将字符串分割为一个List
In [5]: mystr = "shellmad:name:188:27:naneh:xxxx"
In [6]: mylist = mystr.split(":")
In [7]: mylist
Out[7]: ['shellmad', 'name', '188', '27', 'naneh', 'xxxx']
4. 将list拼接为字符串
利用字符串中的join方法,可以将list拼接为字符串
In [8]: "##".join(mylist)
Out[8]: 'shellmad##name##188##27##naneh##xxxx'
5. 对齐调整
字符串对象中有rjust,ljust方法,用于调整字符串的宽度。
In [9]: orgin_str = "hello"
In [10]: orgin_str.rjust(8,"*")
Out[10]: '***hello'
In [12]: orgin_str.ljust(8,"*")
Out[12]: 'hello***'
6. 格式化字符串
python字符串对象中,有format方法,用于格式化字符串。
其中使用”{}”来进行占位,然后通过format方法来传递替换占位符的字符串。
占位常见的方式有两种,按位置,或者按名称
6.1 位置占位
In [15]: str_fmt = "{0} is good one, {1} is another good one"
In [16]: str_fmt.format("zhangsan","lisi")
Out[16]: 'zhangsan is good one, lisi is another good one'
6.2 名称占位
指定key占位
In [24]: str_fmt = "hi, i am {name},i am {age}, i want {dest}"
In [25]: str_fmt.format(name="zhangsan",age=16, dest="money")
Out[25]: 'hi, i am zhangsan,i am 16, i want money'
7. 学习视频地址:字符串对象常见方法