Python-string使用

string 常见操作

'mystr = 'hello nilhy , This is Python demo'

<1>find

检测 str 是否包含在 mystr 中,如果是返回开始的索引值,否则返回 -1

1
2
# 记住,返回的是所在位置索引值,没找到就返回-1
mystr.find(str, start=0, end=len(mystr))

<2> index

跟find()方法一样,只不过如果str不在 mystr中会报一个异常.

1
2
# 如果没有找到,会抛出异常'substring not found'
mystr.index(str, start=0, end=len(mystr))

<3>count

返回 str在start和end之间 在 mystr里面出现的次数

1
mystr.count(str, start=0, end=len(mystr))

<4>replace

把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.

1
2
# 记住这里替换之后会返回一个新的字符串
mystr.replace(str1, str2, mystr.count(str1))

<5>split

以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串

1
2
# 按照空格字符串拆分,参数2为最大拆分数
mystr.split(str=" ", 2)

<6>capitalize

把字符串的第一个字符大写

1
mystr.capitalize()

<7>title

把字符串的每个单词首字母大写

1
2
3
>>> a = "hello jianshu"
>>> a.title()
>>> 'Hello Jianshu'

<8>startswith

检查字符串是否是以 obj 开头, 是则返回 True,否则返回 False

1
mystr.startswith(obj)

<9>endswith

检查字符串是否以obj结束,如果是返回True,否则返回 False.

1
mystr.endswith(obj)

<10>lower

转换 mystr 中所有大写字符为小写

1
mystr.lower()

<11>upper

转换 mystr 中的小写字母为大写

1
mystr.upper()

<12>ljust

返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串

1
mystr.ljust(width)

<13>rjust

返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串

1
mystr.rjust(width)

<14>center

返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

1
mystr.center(width)

<15>lstrip

删除 mystr 左边的空白字符

1
mystr.lstrip()

<16>rstrip

删除 mystr 字符串末尾的空白字符

1
mystr.rstrip()

<17>strip

删除mystr字符串两端的空白字符

1
2
3
4
# 只是去除两端字符串,如果 'jian shu', 中间存在空格,则不去除中间的
>>> a = "\n\t jianshu \t\n"
>>> a.strip()
>>> 'jianshu'

<18>rfind

类似于 find()函数,不过是从右边开始查找.

1
mystr.rfind(str, start=0,end=len(mystr) )

<19>rindex

类似于 index(),不过是从右边开始.

1
mystr.rindex( str, start=0,end=len(mystr))

<20>partition(分区, 分成3段)

把mystr以str分割成三部分,str前,str

1
2
# 返回一个元祖, 参数是按照那个字符串去拆分
mystr.partition(str)

<21>rpartition

类似于 partition()函数,不过是从右边开始.

1
2
# 从右到左,分三段
mystr.rpartition(str)

<22>splitlines

按照行分隔,返回一个包含各行作为元素的列表

1
2
# 分割的字符串,按照\n  分割
mystr.splitlines()

<23>isalpha

如果 mystr 所有字符都是字母 则返回 True,否则返回 False

1
2
# 必须为存字符, 空格都属于其他字符,
mystr.isalpha()

<24>isdigit

如果 mystr 只包含数字则返回 True 否则返回 False.

1
2
# 必须为纯数字, 空格都属于其他字符,
mystr.isdigit()

<25>isalnum

如果 mystr 所有字符都是字母或数字则返回 True,否则返回 False

1
mystr.isalnum()

<26>isspace

如果 mystr 中只能包含空格,则返回 True,否则返回 False.

1
mystr.isspace()

<27>join

mystr 中每个字符后面插入str,构造出一个新的字符串

1
2
3
4
5
6
# 用法 : mystr.join(str)
>>> strs = ['my','name','is', 'hai']
>>> strSpace = ' '
>>> strSpace.join(strs)
# 以下是输出结果
>>> 'my name is hai'

问题:

给定一个字符串aStr,返回使用空格或者’\t’分割后的倒数第二个子串

1
2
3
4
5
6
7
8
testStr = 'haha nihao a \t heihei \t woshi nide \t hao \nnnn'

# 即可以去除以上字符串中的所有转义和空格符号

# 1. 去除\t \n 空格
strList = testStr.strip()
# 2. 得到新的字符串,拼接起来
newStr = ''.join(strList)
0%