Python入门字符串
生活随笔
收集整理的這篇文章主要介紹了
Python入门字符串
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
字符串長度獲取
Python 提供了len()函數(shù)來計(jì)算,并返回字符串的長度,即字符串中單個(gè)元素的個(gè)數(shù)。其基本語法如下:
length = len(target_string)其中:
target_string: 目標(biāo)字符串變量;length: 保存字符串長度的變量;len: 獲取字符串長度的語法關(guān)鍵詞。下面給出了具體的使用示例:
# coding=utf-8 # 創(chuàng)建一個(gè)字符串變量,獲取其長度并打印出來 color = 'It is red' length = len(color) print (length) # 直接在len函數(shù)中引入字符串內(nèi)容獲得其長度,然后打印出來 print(len('This is a circle!'))輸出結(jié)果:
9 17注意: 從輸出結(jié)果可以看到,空格也占一個(gè)字符元素的位置。大小寫轉(zhuǎn)換
Python 提供了upper()和lower()方法,來對字符串進(jìn)行大小寫轉(zhuǎn)換。其中,upper()會(huì)將字符串中的所有字符都轉(zhuǎn)換為大寫,lower()則將所有字符轉(zhuǎn)換為小寫。除此之外,Python 還貼心的提供了title()方法,將字符串所有單詞的首字母變成大寫,而其他字母依然小寫。各個(gè)方法的具體語法如下:
# 將源字符串轉(zhuǎn)換為大寫并存入upper_string變量 upper_string = source_string.upper() # 將源字符串轉(zhuǎn)換為小寫并存入lower_string變量 lower_string = source_string.lower() # 將源字符串每個(gè)詞首字母轉(zhuǎn)換為大寫并存入title_string變量 title_string = source_string.title()其中,source_string為待處理的源字符串。具體使用示例如下:
# coding=utf-8 # 創(chuàng)建一個(gè)字符串say_hello say_hello = 'Dear my Daughter' # 使用upper()方法對say_hello字符串進(jìn)行處理 upper_say_hello = say_hello.upper() # 使用lower()方法對say_hello字符串進(jìn)行處理 lower_say_hello = say_hello.lower() # 使用title()方法對say_hello字符串進(jìn)行處理 title_say_hello = say_hello.title() # 打印輸出四個(gè)字符串 print (say_hello+"\n") print (upper_say_hello+"\n") print (lower_say_hello+"\n") print (title_say_hello+"\n")輸出結(jié)果:
Dear my Daughter DEAR MY DAUGHTER dear my daughter Dear My Daughter注意: 由上述打印結(jié)果可以看出,上述方法的調(diào)用,并不會(huì)對原始的 say_hello字符串產(chǎn)生影響,轉(zhuǎn)換后的字符串會(huì)存入新的變量中。去除字符串首尾空格
Python 提供了strip()方法,可以去除字符串兩側(cè)(不包含內(nèi)部)全部的空格。使用該方法,也可以通過指定參數(shù),去除兩側(cè)指定的特定字符。
注意:在指定參數(shù)時(shí),如果參數(shù)是多個(gè)字符,則該方法會(huì)將多個(gè)字符逐個(gè)去比對,進(jìn)行刪除(區(qū)分大小寫),直到首尾兩側(cè)沒有匹配的字符為止。但是,該方法對字符串中間的字符沒有影響。其基本語法如下:
strip_string1 = source_string.strip() string_strip2 = source_string.strip(target_char)其中:
source_string:待處理的源字符串;strip_string1和strip_string2:處理后的字符串;target_char:需要從源字符串首尾去除的特定字符。具體使用示例如下:
# coding = utf-8 # 創(chuàng)建一個(gè)字符串hello_world hello_world = ' **The world ** is big!* ' # 利用strip()方法處理hello_world字符串 blank_hello_world = hello_world.strip() char_hello_world = hello_world.strip('TH *') # 打印輸出轉(zhuǎn)換后的字符串 print(blank_hello_world) print(char_hello_world)輸出結(jié)果:
**The world ** is big!* he world ** is big!輸出結(jié)果分析:
從第一行打印結(jié)果可以看到,strip()方法去除了源字符串首尾的所有空格,但是并沒有去除字符串中間的空格;從第二行打印結(jié)構(gòu)可以看出,strip()方法將源字符串首尾所有空格、* 以及字符T去掉了,而源字符串中頭部的h因?yàn)槭切懖]有去除。總結(jié)
以上是生活随笔為你收集整理的Python入门字符串的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python安装Whl文件
- 下一篇: 汇编语言:冒泡排序算法将10个数按从小到