1.1.5 Python常用的字符串方法
字符串的方法有很多,可以通过dir来查看:
dir(str)
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__getslice__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘_formatter_field_name_split’, ‘_formatter_parser’, ‘capitalize’, ‘center’, ‘count’, ‘decode’, ‘encode’, ‘endswith’, ‘expandtabs’, ‘find’, ‘format’, ‘index’, ‘isalnum’, ‘isalpha’, ‘isdigit’, ‘islower’, ‘isspace’, ‘istitle’, ‘isupper’, ‘join’, ‘ljust’, ‘lower’, ‘lstrip’, ‘partition’, ‘replace’, ‘rfind’, ‘rindex’, ‘rjust’, ‘rpartition’, ‘rsplit’, ‘rstrip’, ‘split’, ‘splitlines’, ‘startswith’, ‘strip’, ‘swapcase’, ‘title’, ‘translate’, ‘upper’, ‘zfill’]
1,split() 其作用是将字符串根据某个分割符进行分割。
a = “What your name?”
a.split(“ “) #按空格分割,返回一个数组
[‘What’, ‘your’, ‘name?’]
2,去掉字符串两边的空格
S.strip():去掉字符串的左右空格
b=” hello “
b.strip()
‘hello’
S.lstrip():去掉字符串的左边空格
b=” hello “
b.lstrip()
‘hello ‘
S.rstrip():去掉字符串的右边空格
b.rstrip()
‘ hello’
3,字符串大小写转换
S.upper() 小写转大写
a=”hello”
a.upper()
‘HELLO’
S.lower() 大写转小写
b=”AAA”
b.lower()
‘aaa’
S.capitalize() 字符串的首字母变大写
a=”hello world”
a.capitalize()
‘Hello world’
S.isupper() 判断字符串是否都是大写
b=”AAA”
b.isupper()
True
b=”AAb”
b.isupper()
False
S.islower() 判断字符串是否都是小写
a=”hello”
a.islower()
True
a=”Hello”
a.islower()
False
S.istitle() 判断每个词是否只有首字母大写
a=”Hello World”
a.istitle()
True
a=”Hello world”
a.istitle()
False
a=”HEllo World”
a.istitle()
False
S.title() 字符串转换成首字母大写
a=”hello world”
a.title()
‘Hello World’
4,join连接字符串
用“+”能够连接字符串,但不是什么情况下都能够如愿。比如,将列表(列表是另外一种类型)中的每个字符(串)元素拼接成一个字符串,并且用某个符号连接,但如果用“+”会比较麻烦。用字符串的join方法就比较容易实现。
a=”www.baidu.com”
b=a.split(“.”)
b
[‘www’, ‘baidu’, ‘com’]
“*“.join(b)
‘www*baidu*com’
5,字符串格式化输出
print “Hello {}“. format (“World”)
Hello World
print “hello {world}“. format (world=”zhangsan”)
hello zhangsan
print “name is {name} and age is {age}“. format (name=”zhangsan”,age=”26”)
name is zhangsan and age is 26
print “name is {0} and age is {1}“. format (“zhangsan”,”26”)
name is zhangsan and age is 26
还没有评论,来说两句吧...