Python字符串到底要如何编写


Python字符串的使用中有不少的知识需要我们学习。其实不管在什么样的环境下都是需要掌握相关的字符串的应用。下面我们就来看看Python字符串具体是如何编写的。

  1. #coding:utf-8   
  2. #字符串的操作   
  3. #使用中括号[]可以从字符串中取出任一个连续的字符   
  4. #注意:中括号内表达式是字符串的索引,它表示字符在字符串内的位置,   
  5. #中括号内字符串第一个字符的索引是0,而不是1   
  6. #len返回字符串的长度   
  7. test_string = "1234567890"   
  8. print test_string[0] #result = 1 
  9. print test_string[1] #result = 2 
  10. print test_string[9] #result = 0 
  11. print len(test_string) #result = 10 
  12. #使用for循环遍历字符串  
  13. for i in test_string:  
  14. print i  
  15. if (i == '5'):  
  16. print "Aha,I find it!"  
  17. print type(i) #<type 'str'>20  
  18. #提取字符串的一部分  
  19. #操作符[n:m]返回字符串中的一部分。从第n个字符串开始,到第m个字符串结束。  
  20. #包括第n个,但不包括第m个。  
  21. #如果你忽略了n,则返回的字符串从索引0开始  
  22. #如果你忽略了m,则字符串从n开始,到最后一个字符串  
  23. test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 
  24. print test_string[0:5] #result = 'ABCDE' 
  25. print test_string[8:11] #result = 'IJK' 
  26. print test_string[:6] #result = 'ABCDEF' 
  27. print test_string[20:] #result = 'UVWXYZ' 
  28. print test_string[:] #result = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 

以上就是对Python字符串在使用中的代码介绍。

评论关闭