---python_string---操作字符串的方法

1.移除指定字符

 1 username = input("please input you name:")
 2 # strip 移除前后指定的字符,默认是空格(包括'\n', '\r',  '\t',  ' ')
 3 if username.strip() == 'lufei':
 4         print("hello %s" % username)
 5 name = 'abcd'
 6 
 7 print(name.lstrip('a'))  # 移除左边指定字符
 8 print(name.rstrip('d'))  # 移除右边指定字符
 9 # please input you name:lufei
10 # hello lufei
11 # bcd
12 # abc

2.拆与合

 1 oneprice = " lufei, shanzhi, soulong "
 2 oneprice.split(",")
 3 print(oneprice)
 4 #  lufei, shanzhi, soulong
 5 twoprice = oneprice.split(",")
 6 print(twoprice)  # 变成列表了
 7 [' lufei', ' shanzhi', ' soulong ']
 8 print('|'.join(oneprice))
 9 #  |l|u|f|e|i|,| |s|h|a|n|z|h|i|,| |s|o|u|l|o|n|g| 
10 print('|'.join(twoprice))
11 #  lufei| shanzhi| soulong 

3.索引

1 # 如果索引为负数,就是相当于从后向前数
2 str = "hello world"
3 print(str[0])
4 # h
5 print(str[-1])
6 # d

4.无穷无尽

 1 # 首字母大写 capitalize()
 2 myname = "li"
 3 print(myname.capitalize())
 4 # Li
 5 # format() 字符串格式化
 6 str = "hi,{name},you look {status}"
 7 print(str.format(name = 'liming', status = 'cute'))
 8 # hi,liming,you look cute
 9 str = "hi,{0},you look {1}"
10 print(str.format("liming","cute"))
11 # hi,liming,you look cute
12 # 切片
13 name = "libai"
14 print(name[2:4])
15 # ba
16 # center()方法返回集中在长度宽度的字符串,默认一个空格
17 print(name.center(30, '-'))
18 # ------------libai-------------
19 # 返回索引,如果没找到返回-1
20 print(name.find('l'))
21 # 判断是不是数字
22 if name.isdigit():
23     print("int")
24 else:
25     print("string")
26 # 判断字符串是否全是字符或数字并至少有一个字符,有特殊字符返回false
27 str2 = 'asd&sad'
28 print(str2.isalnum())
29 # False

 5.字符串方法实在太多,每种语言都是这样。实在不行,只能列举出来,知道大概就好。

  1. str.rjust:右对齐
  2. str.ljust:左对齐
  3. str.center:中间对齐
  4. str.zfill:默认的方式
  5. str.find:字符串查找,没有返回-1
  6. str.index:查找字符串位置,没有返回错误
  7. str.rfind:从右开始查找
  8. str.rindex:同上
  9. str.count:统计字符串出现的次数
  10. str.replace:字符串替换
  11. str.strip:去除字符串开头末尾的空格
  12. str.lstrip:去除左边空格
  13. str.rstrip:去除右边空格
  14. str.expandtabs:把字符串里的table换成等长的空格
  15. str.lower:
  16. str.upper:
  17. str.swapcase:将字符串字符大小写反转
  18. str.capitalize:字符串首字符大写
  19. str.title:字符串中首字母大写 
  20. str.split:字符串拆分成列表
  21. str.splitlines:将字符串中按行拆分放到列表中
  22. '-'.join(strList):用‘-’将列表strList连接成字符串
  23. str.startswith:测试字符串是否是以指定字符开头的
  24. str.endswith:测试字符串是否是以指定字符结尾的
  25. str.isalum:判断字符串是否全是字符或数字并至少有一个字符
  26. str.isalpha:判断字符串是否全是字母
  27. str.isdigit:判断字符串是否全是数字
  28. str.isspace:判断字符串是否含有空格
  29. str.islower:判断字符串是否全是小写
  30. str.isupper:判断字符串是否全是大写
  31. str.istitle:判断首字母是否是大写
  32. import string
  33. string.atoi("123",base=10/8/16):转换字符串到int类型的数字
  34. string.atol:转换字符串到长整形数字
  35. string.atof:转换字符串到浮点型

 

posted @ 2016-12-06 21:50  心悲动我神  阅读(2726)  评论(0编辑  收藏  举报