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
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值