Python 字符串常见操作总结

介绍Python常见的字符串处理方式

1、字符串连接

# 1、最简单方式 +
>>> 'hello'+' world'
'hello world'
# 2、替换
>>> "%s %s" %('hello',' world')
'hello  world'
# 3、join方法
>>> ' '.join(['hello','world'])
'hello world'

2、字符串转数组

a = 'My name is Jason'
#使用split(str="", num=string.count(str)) 方法根据不同的分割符转,也可指定分割次数,可使用 ' '.join方法转回
>>> 'My name is Jason'.split(' ')
['My', 'name', 'is', 'Jason']
>>> ' '.join(['My', 'name', 'is', 'Jason'])
'My name is Jason'

3、字符串比较

>>> 'hello' == 'hello'
True
>>> 'hello' != 'hello'
False
>>> '123' is 123
False
>>> '123' is not 123
True
# python2中还可以使用cmp,python3改成如下方式
>>> import operator
>>> operator.eq('world',' world')
False

4、字符串查找

#字符串查找
>>> ml = 'Machine Learning'
>>> 'Le' in ml
True
>>> ml.find('n')
5
>>> ml.rfind('n')
14
>>> ml.index('n')
5
>>> ml.rindex('n')
14
>>> ml.find('N')
-1
>>> ml.index('N')
Traceback (most recent call last):
  File "<pyshell#176>", line 1, in <module>
    ml.index('N')
ValueError: substring not found

5、字符串替换

#将字符串中数字替换为空
>>> '123hello'.replace('123','')
'hello'
#正则替换
>>> import re
>>> re.sub("[0-9]",'','123hello')
'hello'

6、字符串首尾匹配

>>> 'cat.jpg'.startswith('cat')
True
>>> 'cat.jpg'.startswith('cat',0,3)
True
>>> 'cat.jpg'.endswith('.jpg')
True
>>> 'cat.jpg'.endswith('.jpg',-4)
True

7、字符串空格处理

>>> s = '  Hello World   '
>>> s.strip()
'Hello World'
>>> s.lstrip()
'Hello World   '
>>> s.rstrip()
'  Hello World'
#扩展
>>> 'www.example.com'.lstrip('www.')
'example.com'
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'

8、字符串格式化、数字及大小写判断、长度补全

#字符串的格式化
>>> '{name},{sex},{age}'.format(age=15,sex='male',name='小安')
'小安,male,15'
>>> '{1},{0},{2}'.format('15','小安','male')
'小安,15,male'
>>> '{},{},{}'.format('小安', '15','male')
'小安,15,male'

#如果字符串中的所有字符都是数字,并且至少有一个字符,则返回真,否则返回假
>>> '123'.isdigit()
True
>>> '123一二三'.isdigit()
False
#isnumeric 是所有字符都是数字字符返回真
>>> '123一二三'.isnumeric()
True

#字符串是否大小写判断
>>> 'abc'.islower()
True
>>> 'Abc'.islower()
False
>>> 'ABC'.isupper()
True

#首字母大写
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
#正则处理方式
>>> import re
>>> def titlecase(s):
...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."

#返回指定长度字符串,前面补0,一般存csv文件中含00开头的字符0会被抹掉
>>> code = '1'
>>> code.zfill(6)
'000001'

#字符串长度及遍历
>>> s = '混蛋哥'
>>> len(s)
3
>>> for i in s:
    print(i)
混
蛋
哥
>>> 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容