Python字符串到底要如何編寫
作者:佚名
Python字符串在使用的時候有不少的知識需要我們學習,其中就有相關代碼的編寫。下面我們就看看如何進行代碼的編寫。
Python字符串的使用中有不少的知識需要我們學習。其實不管在什么樣的環境下都是需要掌握相關的字符串的應用。下面我們就來看看Python字符串具體是如何編寫的。
- #coding:utf-8
- #字符串的操作
- #使用中括號[]可以從字符串中取出任一個連續的字符
- #注意:中括號內表達式是字符串的索引,它表示字符在字符串內的位置,
- #中括號內字符串第一個字符的索引是0,而不是1
- #len返回字符串的長度
- test_string = "1234567890"
- print test_string[0] #result = 1
- print test_string[1] #result = 2
- print test_string[9] #result = 0
- print len(test_string) #result = 10
- #使用for循環遍歷字符串
- for i in test_string:
- print i
- if (i == '5'):
- print "Aha,I find it!"
- print type(i) #<type 'str'>20
- #提取字符串的一部分
- #操作符[n:m]返回字符串中的一部分。從第n個字符串開始,到第m個字符串結束。
- #包括第n個,但不包括第m個。
- #如果你忽略了n,則返回的字符串從索引0開始
- #如果你忽略了m,則字符串從n開始,到最后一個字符串
- test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
- print test_string[0:5] #result = 'ABCDE'
- print test_string[8:11] #result = 'IJK'
- print test_string[:6] #result = 'ABCDEF'
- print test_string[20:] #result = 'UVWXYZ'
- print test_string[:] #result = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
以上就是對Python字符串在使用中的代碼介紹。
【編輯推薦】
責任編輯:張浩
來源:
博客園