python字符串总结

1. 下标和切片
列表与元组支持下标索引好理解,字符串实际上就是字符的数组,所以也支持下标索引。

  • 下标

    如果想取出部分字符,那么可以通过下标的方法,(注意python中下标从 0 开始)

>>> name="abcde"
>>> print(name[0])#注意python中下标从 0 开始
a
>>> print(name[4])
e
>>> 
  • 切片
    -
    切片是指对操作的对象截取其中一部分的操作。字符串、列表、元组都支持切片操作。

切片的语法:[起始:结束:步长],注意分隔符号是”:”

注意:选取的区间属于左闭右开型,即从”起始”位开始,到”结束”位的前一位结束(不包含结束位本身)。

>>> print(name[0:3])#取 下标0~2 的字符
abc
>>> print(name[0:4])
abcd
>>> print(name[0:5])#取 下标0~4 的字符
abcde
>>> print(name[2:]) #取下标2(包括2)以后所有的字符
cde
>>> print(name[:2])#取下标2(不包括2)以前所有的字符
ab
>>> print(name[::2])#正向隔1位取字符
ace
>>> print(name[::-2])#反向隔1位取字符
eca

想一想:(面试题)给定一个字符串aStr, 请反转字符串

>>> name="aStr"
>>> print(name[::-1])
rtSa

2. 字符串常见操作
如有字符串mystr = ‘hello world itcast and itcastcpp’,以下是常见的操作
<1>find
检测 str 是否包含在 mystr中,如果是返回开始的索引值,否则返回-1

>>> print(mystr.find("itcast"))
12
>>> print(mystr.find("itcast",0,11))
-1

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

mystr.index(str, start=0, end=len(mystr))

>>> print(mystr.index("itcast",0,11))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

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

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

>>> print(mystr.count("itcast"))     
2

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

mystr.replace(str1, str2, mystr.count(str1))

>>> name="hello world ha ha" 
>>> print(name.replace("ha","HA"))
hello world HA HA
>>> print(name.replace("ha","HA",1))
hello world HA ha

<5>split
以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串
分隔后的结果已列表展现
mystr.split(str=” “, 2)

str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
spilt()较为常用

>>> print(name.split(' '))   
['hello', 'world', 'ha', 'ha']
>>> print(name.split(' ',2))#分隔出2个字符串,剩下的为一个子字符串
['hello', 'world', 'ha ha']
>>> print(name.split(' ',3))
['hello', 'world', 'ha', 'ha']
>>> print(name.split(' ',4))#个数超出时,不会报错
['hello', 'world', 'ha', 'ha']
>>> print(name.split(' ',5))
['hello', 'world', 'ha', 'ha']

<6>capitalize
把字符串的第一个字符大写

mystr.capitalize()

>>> print(name.capitalize())
Hello world ha ha

<7>title
把字符串的每个单词首字母大写

>>> print(name.title())     
Hello World Ha Ha
>>> name1="Hello world"
>>> print(name1.title())
Hello World

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

mystr.startswith(obj)

>>> print(mystr.startswith("hello"))
True
>>> print(mystr.startswith("Hello"))
False

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

mystr.endswith(obj)
<10>lower
转换 mystr 中所有大写字符为小写

mystr.lower()

>>> name="HELLO World"
>>> print(name.lower())
hello world

<11>upper
转换 mystr 中的小写字母为大写

mystr.upper()
<12>ljust
返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串

mystr.ljust(width)

>>> name="hello"
>>> print(name.ljust(10))
hello     
>>> name.ljust(10)
'hello     '

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

mystr.rjust(width)
<14>center
返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

mystr.center(width)

>>> print(name.center(20)) 
       hello        
>>> name.center(20)

<15>lstrip
删除 mystr 左边的空白字符

mystr.lstrip()

>>> name="      hello      "
>>> print(name.lstrip())    
hello      
>>> name.lstrip()           
'hello      '

<16>rstrip
删除 mystr 字符串末尾的空白字符

mystr.rstrip()
<17>strip
删除mystr字符串两端的空白字符

>>> print(name.strip()) 
hello
>>> name.strip()       
'hello'

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

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

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

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

<20>partition
把mystr以str分割成三部分,str前,str和str后

mystr.partition(str)

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

mystr.rpartition(str)

>>> mystr.partition("itcast")
('hello world ', 'itcast', ' and itcastcpp')
>>> mystr.rpartition("itcast")
('hello world itcast and ', 'itcast', 'cpp')

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

>>> name="hello\nworld"
>>> print (name)       
hello
world
>>> name.splitlines()
['hello', 'world']

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

mystr.isalpha()

<24>isdigit
如果 mystr 只包含数字则返回 True 否则返回 False.
mystr.isdigit()

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

mystr.isalnum()

<26>isspace
如果 mystr 中只包含空格,则返回 True,否则返回 False.

mystr.isspace()

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

mystr.join(str)

>>> str=" "
>>> list=["hello","world","haha","666"]
>>> str.join(list)
'hello world haha 666'
>>> str="_"       
>>> str.join(list)
'hello_world_haha_666'

可以用于除去空白字符后生成新的字符串

>>> a="hello world"
>>> a.split()
['hello', 'world']
>>> "".join(a.split())
'helloworld

练习题1:如下字符串,含有空格和换行符,返回使用空格或者’\t’分割后的倒数第二个子串
test=”hello world \t ha he \nhei \nher”
以\t分割
newTest=test.split(“\t”)
print(newTest)
print(“以\t\t分割后的倒数第二个子串:%s”%newTest[len(newTest)-2])
以空格分割
newTest=test.split()
print(newTest)
print(“以空格分割后的倒数第二个子串:%s”%newTest[len(newTest)-2])
结果如下:
[‘hello world ‘, ’ ha he \nhei \nher’]
以\t 分割后的倒数第二个子串:hello world
[‘hello’, ‘world’, ‘ha’, ‘he’, ‘hei’, ‘her’]
以空格分割后的倒数第二个子串:hei

练习题2:”hello world” 字符串统计的结果为: h:1 e:1 l:3 o:2 d:1 r:1 w:1

方法1a="hello shanghai china"

--去空格

b=''.join(a.split())

--创建空列表,用于存放去重后字符

li=[]

for i in b:
        if i not in li:
                li.append(i)

for i in li:
        print("%s:%d"%(i,a.count(i)))

 方法2:
>>> string = 'hello world'
>>> { a:string.count(a) for a in set(string.replace(' ','')) }
{'h': 1, 'e': 1, 'w': 1, 'l': 3, 'o': 2, 'd': 1, 'r': 1}

猜你喜欢

转载自blog.csdn.net/weixin_40283570/article/details/80682371