---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:轉換字符串到浮點型

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM