三. 字符串常用方法。pycharm中操作
1》示例:
#/usr/bin/python
#coding=utf-8
#@Time :2017/10/11 16:20
#@Auther :liuzhenchuan
#@File :demon-str.py
s = ‘hello‘
print(dir(s))
print(s[0],s[1],s[2])
运行如下::
[‘__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‘]
(‘h‘, ‘e‘, ‘l‘)
2》常用字符串方法
#find 查找
#replace 替换
#split 以什么为分割符
#join
#strip
#format
-----find 解析
rfind:从右边开始找
lfind:从左边开始找
s1 = ‘dingeigliuzhenchuan08jo‘
print(s1.find(‘liu‘))
print(s1.find(‘abdliu‘))
运行如下:
7
-1 //找不到就会返回负1
----replace 解析。替换
s1 = ‘dingeigliuzhenchuan08jo‘
print(s1.replace(‘liu‘,‘hello‘))
运行如下:
dingeighellozhenchuan08jo
---split解析,返回为列表。以什么为分割符
s2 = ‘ttion:eottn:aacng‘
print(s2.split(‘:‘))
运行如下:
[‘ttion‘, ‘eottn‘, ‘aacng‘]
----join() 连接字符串数组。将字符串,元组,列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
----os.path.join() 将多个路径组合后返回
s3 = ‘12:34:56‘
print(‘word‘.join(s3))
print(‘word‘.join(s3.split(‘:‘)))
运行如下:
1word2word3word4word5word6
12word34word56
---strip() 方法用于移除字符串头尾指定的字符(默认为空格)
strip() 方法语法:
str.strip([chars])
chars:移除指定的字符串
rstrip():从右边开始去掉
lstrip():从左边开始去掉
#/usr/bin/python
#coding=utf-8
#@Time :2017/10/12 21:12
#@Auther :liuzhenchuan
#@File :字符串.py
s1 = ‘ 11ab 11cd 11 ‘
print(s1)
print(s1.rstrip())
print(s1.lstrip())
print s1.strip(‘ 11‘) //移除两个空格和两个11的字符
运行如下:
11ab 11cd 11 //打印s1字符串
11ab 11cd 11 //从右边开始去掉空格,左边留有空格
11ab 11cd 11 //从左边开始去掉空格,右边留有空格
ab 11cd
---format() 字符串格式化
%s:代表的是字符串
%d:代表的是整数‘
%f:代表的是浮点型
#format 格式化字符串
name = ‘liuzhenchuan‘
print ‘hello ‘+name
print ‘hello %s‘ % name
print(‘hello {0}‘).format(name)
运行如下:
hello liuzhenchuan
hello liuzhenchuan
hello liuzhenchuan
多个变量的情况
#format 格式化字符串
name = ‘liuzhenchuan‘
age = 20
print(‘hello {0},my age is: {1}‘.format(name,age))
print ‘{name}:{age}‘.format(name=‘ajing‘,age=‘20‘)
运行如下:
hello liuzhenchuan,my age is: 20
ajing:20