python中的字符串处理与列表

字符串处理


\:转义字符

索引:

 s="dream in python"
 s[0]                                                 ###显示第一个字符
 Out[3]: 'd'

切片:

 s[0:5]                                               ###显示出前5个字符
 Out[6]: 'dream'

 s[0:-1]                                              ###显示出0到倒数第二个字字符符                                              
 Out[7]: 'dream in pytho'

 s[:]                                                 ###显示出多有字符
 Out[8]: 'dream in python'

 s[::-1]                                              ###反转 
 Out[18]: 'nohtyp ni maerd'

判断子串

 'python' in s                                        ###存在就为真
 Out[9]: True

 'python' not in s                                    ###存在为假
 Out[10]: False

重复

 "*"*10                                               ###打印10个*
 Out[11]: '**********'

连接:

 "*"*10+"oldgao"+"*"*10                             ###+:连接的作用
 Out[12]: '**********dream_ya**********'

计算长度:

 len(s)                                               ###查看字符串的长度
 Out[13]: 15

变量名合法性判断

规则:
1.变量名由字母,数字或者下划线组成
2.变量名只能以字母或者下划线开头

 while True:
     s = raw_input("请输入一个变量名:")
     if s[0].isalpha() or s[0] == "_":
         for i in s[1:]:
             if i.isalnum() or i == "_":
                     continue
             else:
                     print "不合法!"
                     break
         else:
             print "%s合法"%(s)
     else:
         print "不能以数字开头"

字符串常用操作:


 str="dream"
 str.capitalize()                                    ###将字符串首字母大写,并返回新的首字母大写后的字符串
 Out[15]: 'Dream'

str.center(width[,fillchar]):

返回一个长为width的新字符串,在新字符串中原字符居中,其他部分用fillchar指定的符号填充,未指定时通过空格填充

 str="dream"
 str.center(10,'*')
 Out[19]: '**dream***'

str.count(sub[, start[, end]]) -> int

返回sub在str中出现的次数,如果start与end指定,则返回指定范围内的sub出现次数

 str="hello python"
 str.count("o")
 Out[21]: 2

str.endswith(suffix[, start[, end]])

判断字符串是否以suffix结束

 str="hello python"
 str.endswith("n")
 Out[22]: True
 str.endswith("o")
 Out[23]: False

str.startswith(prefix[, start[, end]])

判断字符串是否以suffix开始

 str="hello python"
 str.startswith("h")
 Out[24]: True
 str.startswith("p")
 Out[25]: False

str.index(sub[,start[,end]])

其和str.find(sub[,start[,end]])一样,只是错误报错不同(返回为-1),判断sub是否在str中,存在返回索引值,如果sub不存在时抛出ValueError异常

 str="hello python"
 str.index("p")
 Out[28]: 6
 str.index("i")
 ValueError: substring not found

str.join(seq)

以str作为分隔符,将序列seq中的所有元素合并为一个新的字符串

 str="hello python"
 print " ".join(str)
 h e l l o   p y t h o n

str.replace(old,new[,count])

将str中的old字符串替换为new字符串,并将替换后的新字符串返回,如果count指定,则只替换前count个字符串

 str="hello python"
 str.replace("python","world")
 Out[43]: 'hello world'

好未来笔试题:输入两个字符串,string1字符串中不能包含string2字符串带的字符

 string1 = raw_input("please input string1:")
 string2 = raw_input("please input string2:")
 for i2 in string2:
     string = string1.replace(i2,"")
     string1 = string
 print string

str.split([sep[,maxsplit]])

以sep字符串作为分割符对str进行切割,默认为空格,maxsplit代表切割的此处

 str="hello python"
 str.split("o")
 Out[49]: ['hell', ' pyth', 'n']

str.strip([chars])

返回一字符串,将str中首尾包含指定的chars字符删除的字符串,未指定时,删除首尾的空格

 str="a b a b a"
 str.strip("a")
 Out[55]: ' b a b '

字母和数字判断(其和shell类似)

 str.isalnum()                                          ###判断是否都是字母或数字
 str.isalpha()                                          ###判断是否都是字母
 str.isdigit()                                          ###判断是否都是数字
 str.islower()                                          ###判断是否都是小写
 str.isspace()                                          ###判断是否都是英文空格
 str.istitle()                                          ###判断是不是都是标题(有大小写且是首字母)
 str.isupper()                                          ###判断是不是都为大写字母

华为机试题:输入字符串,分别统计字母,数字,空格,特殊符号的个数

 s = raw_input("please input string:")
 string, Num, space, Else = 0, 0, 0, 0
 for i in range(0, len(s)):
     if s[i] == " ":
         space += 1
     elif s[i].isdigit():
         Num += 1
     elif s[i].isalpha():
         string += 1
     else:
         Else += 1
 print "字母:%d\n数字:%d\n空格:%d\n其他:%d" % (string, Num, space, Else)

枚举:

方法一:

 a = raw_input("请输入:")
 b = len(a)
 for i in range(0,b):
         print i,a[i]

方法二:

 for i,j in enumerate(hello):
     print i,j

素数 :

 Times = 1
 Prime_Num = input("please input num:")
 if Prime_Num == 2:
     print "The number of primes:1"
     exit()
 elif Prime_Num > 0:
     for i in range(0, Prime_Num):
         if (4 * i + 1) < Prime_Num or (4 * i - 1) < Prime_Num:
             Times += 1
 print "The number of primes:%d" %(Times)

列表


定义一个空列表:

 list = []

定义一个包含元素的列表,元素可以是任意类型,包括数值类型,列表,字符串等均可

 list = ["hello", 4, 'python']

索引:

 list = ["hello", 4, 'python']
 list[0]
 Out[57]: 'hello'

切片:
• 0代表从哪个索引开始切片;
• 3代表切片到哪个位置,并且不包含第三个索引;
• 2代表切片的步长;

 list = ["hello", 4, 'python']
 list[0:3:2]
 Out[58]: ['hello', 'python']

append添加(单个):

 list = ["hello", 4, 'python']
 list.append("dream")
 print list
 ['hello', 4, 'python', 'dream']

extend添加(多个):

 list = ['hello', 4, 'python', 'dream']
 list1 = ["1","2","3"]
 list.extend(list1)
 print list
 ['hello', 4, 'python', 'dream', '1', '2', '3']

inset添加(指定位置):

 list = ['hello', 4, 'python', 'dream']
 list.insert(1,"2")
 print list
 ['hello', '2', 4, 'python', 'dream']

修改元素:

 list = ['hello','python']
 list[1] = "dream"
 print list
 ['hello', 'dream']

index索引查看:

 list = ['hello','python']
 list.index("python")
 Out[76]: 1

count元素出现的此数:

 list = ['12', '1', '13', '1']
 list.count("1")
 Out[79]: 2

删除元素list.remove(list[ ]):

 list = ['12', '1', '13', '1']
 list.remove("1")
 list
 Out[82]: ['12', '13', '1']

删除列表del:

 list = ['12', '1', '13', '1']
 del(list)
 list                                                 ###无结果输出

猜你喜欢

转载自blog.csdn.net/u010489158/article/details/81137439
今日推荐