python基礎之字符串類型


一、python字符串類型概述

定義:在單引號\雙引號\三引號內,由一串字符組成 name='Test'

name = 'test'
print(type(name))
--------------------------------------------
<class 'str'>

字符串:在引號(單引號,雙引號,三引號)里定義的一堆字符
狀態:描述性的內容,比如名字,性別,國籍

如果字符串內部包含單引或者雙引,需要用到轉義字符 \ 來標識:

print("I\'m \"ok\"")
print('\\\n\\')
print(r'\\\n\\') #r"表示引號內的內容不轉義
---------------------------------------------------------
I'm "ok"
\
\
\\\n\\

二、字符串的索引(index)

在python當中所有有序的序列都是由索引概念的,它們的區別在於序列是否可以被修改;

索引在我們初學的時候我們可以理解為字符串的下標;

字符串里的每一個個體都被稱作字符也是該字符串的一個元素;

比如字符串‘while’,可以按照下圖理解其下標概念,索引號從0開始;

w

h

i

l

e

0

1

2

3

4

索引的用法,取單個元素時,使用字符串[索引值] ,索引值為對應元素的索引號;

print("while"[4])
--------------------------------
e

字符串截取:字符串[start:end],得到對應索引范圍的元素,該范圍包含起始端,不包含結尾端,默認截取的方向是從左往右的;

print("while"[0:3])
-------------------------------
whi

步長截取:字符串[start:end:step] 按照step步長進行隔取;

print("hello world"[0:8:2])
--------------------------------------------
hlow

切片的語法:[起始:結束:步長]

注意:選取的區間屬於左閉右開型,即從"起始"位開始,到"結束"位的前一位結束(不包含結束位本身)。

默認取法:字符串[start:end,step] 這三個參數都有默認值、start;默認值為0;end  默認值未字符串結尾元素;step  默認值為1

str = "hello world"
print(str[:])
print(str[:6])  #顧頭不顧尾
print(str[-1])  #取反:字符串[負數],從右往左取
print(str[:-1])
print(str[1:7:2])  
-----------------------------------------------------------
hello world
hello 
d
hello worl
el 

 三、字符串的方法

 

 

字符串的查找

count

計數功能,返回自定字符在字符串當中的個數

find

查找,返回從左第一個指定字符的索引,找不到返回-1

index

查找,返回從左第一個指定字符的索引,找不到報錯

例子1:

str = "hello world"
print(str.count('o'))  # 統計次數
print(str.find('w'))  # 查找
print(str.find('x'))  # 查找,找不到返回-1
# print(str.index('x'))  # 查找,找不到報錯
------------------------------------------------------------
2
6
-1

字符串的分割

splitlines

按照行分隔,返回一個包含各行作為元素的列表,按照換行符分割

例子2:

mystr = "hello world java\n welecome to \nbeijing" # \n表示換行
print(mystr)
print(mystr.splitlines())   #  按照行分割,返回的就是列表
-------------------------------------------------------------------
hello world java
 welecome to 
beijing
['hello world java', ' welecome to ', 'beijing']

字符串的替換

replace

從左到右替換指定的元素,可以指定替換的個數,默認全部替換

 例子3:

print("hello".replace('l','k'))
-----------------------------------------
hekko

字符串的修飾

center

讓字符串在指定的長度居中,如果不能居中左短右長,可以指定填充內容,默認以空格填充

ljust

讓字符串在指定的長度左齊,可以指定填充內容,默認以空格填充

rjust

讓字符串在指定的長度右齊,可以指定填充內容,默認以空格填充

format

按照順序,將后面的參數傳遞給前面的大括號

strip

默認去除兩邊的空格,去除內容可以指定

rstrip

默認去除右邊的空格,去除內容可以指定

lstrip

默認去除左邊的空格,去除內容可以指定

 例子4:

str = "   Love   "
print(str.center(50,"*")) #讓字符串在指定的長度居中,
print(str.ljust(30,"*")) #讓字符串在指定的長度左齊
print(str.rjust(30,"*")) #讓字符串在指定的長度右齊
print(str.rstrip()) #默認去除右邊的空格
print(str.lstrip()) #默認去除左邊的空格
#format 按照順序,將后面的參數傳遞給前面的大括號
python = '{} love {}'
print(python.format('I','you'))
----------------------------------------------------------------
********************   Love   ********************
   Love   ********************
********************   Love   
   Love
Love   
I love you

 

 

 

 

字符串的變形

upper

將字符串當中所有的字母轉換為大寫

lower

將字符串當中所有的字母轉換為小寫

swapcase

將字符串當中所有的字母大小寫互換

title

將字串符當中的單詞首字母大寫,單詞以非字母划分

capitalize

只有字符串的首字母大寫

例子5: 

print("hello".upper())
print("HELLO".lower())
print("HELLO world".swapcase())
print("hello world".title())
print("hello world".capitalize())
-----------------------------------------------------
HELLO
hello
hello WORLD
Hello World
Hello world

 

 

 

 

字符串的判斷

isalnum

判斷字符串是否完全由字母或數字組成

isalpha

判斷字符串是否完全由字母組成

isdigit

判斷字符串是否完全由數字組成

isupper

判斷字符串當中的字母是否完全是大寫

islower

判斷字符串當中的字母是否完全是小寫

istitle

判斷字符串是否滿足title格式

isspace

判斷字符串是否完全由空格組成

startswith

判斷字符串的開頭字符

endswith

判斷字符串的結尾字符

split

判斷字符串的分隔符切片

例子6:

#isalnum
print("123456e".isalnum()) #判斷字符串是否完全由字母或數字組成
#isdigit
print("123456".isdigit()) #判斷字符串是否完全由數字組成
#isupper
print("HELLO".isupper()) #判斷字符串當中的字母是否完全是大寫
#islower
print("hello".islower()) #判斷字符串當中的字母是否完全是小寫
#istitle
print("Hello World".istitle()) #判斷字符串的開頭首字母是否大寫
#isalpha
print("HelloWorld".isalpha()) #判斷字符串是否完全由字母組成
# startwith
print("hello world 2.txt".startswith("hello")) #判斷字符串的開頭
#endswith
print("hello world 2.txt".endswith(".txt")) #判斷字符串是否.txt結尾
#replace
print("hello world".replace("hello","LOVE")) #替換
#split
print("hello world".split(" ")) # 按照空格切 ,結果變成列表的元素
# 拓展:
txt = "Gologle#Runoob#Taobao#Facebook"
# 第二個參數為 1,返回兩個參數列表
x = txt.split("e", 1)
print(x)
-------------------------------------------------------------------
True
True
True
True
True
True
True
True
LOVE world
['hello', 'world']
['Gologl', '#Runoob#Taobao#Facebook']

 例子7:

a = "hello 世界"
#encode轉碼
res = a.encode('utf-8')
print(res)
------------------------------------
b'hello \xe4\xb8\x96\xe7\x95\x8c'
-----------------------------------------------
a = "hello 世界"
#encode轉碼
res = a.encode('utf-8')
# print(res)
#decode解碼
print(res.decode('utf-8'))
-------------------------------------
hello 世界

例子8:

#format格式化輸出
name = 'qqq'
age =23
# res = 'my name is {},my age is {}'.format(name,age) #方法一
# res = 'my name is {1},my age is {0}'.format(age,name)   #方法二
res = 'my name is {name},my age is {a};my small name is {name}'.format(name=name,a=age) #方法三
print(res)
----------------------------------------------------------------------------
my name is qqq,my age is 23;my small name is qqq

例子9:

# join把可迭代對象變成字符串,括號里可以是字典,列表,元組,字符串
res = '22'.join(['name','age'])   #列表
# res = '22'.join(('name','age'))   #元組
print(res)
res = '22'.join('name')   #字符串
print(res)
--------------------------------------------------------------------
name22age
n22a22m22e

例子10:

#strip是去除左右兩邊的字符,默認為空格
a = '-----====畢洪態====='
print(a)
res = a.strip('=')
b = res.strip('-')
print(b)
---------------------------------------------------
-----====畢洪態=====
====畢洪態

例子11:

#%s,%d,%f占位符
res = 'my name is %s; my age is %s' % ('李國祥',23)
print(res)
res = 'my high is %.2f' % 185.2322
print(res)
-----------------------------------------------------------------
my name is 李國祥; my age is 23
my high is 185.23

 


免責聲明!

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



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