1. 程式人生 > >python3字符串操作總結

python3字符串操作總結

包括 min upper opera false 查找 特殊字符 判斷字符串 asc

  • 字符串截取
>>>s = hello
>>>s[0:3]
he 
>>>s[:] #截取全部字符
hello
  • 消除空格及特殊符號
s.strip() #消除字符串s左右兩邊的空白字符(包括‘\t‘,‘\n‘,‘\r‘,‘‘)
 
s.strip(0) #消除字符串s左右兩邊的特殊字符(如‘0‘),字符串中間的‘0‘不會刪除
例如:
>>>s = 000hello00world000
>>>s.strip(0)
hello00world
 
s.strip(12)等價於s.strip(
21) 例如: >>>s = 12hello21 >>>s.strip(12) hello lstrip,rstrip 用法與strip類似,分別用於消除左、右的字符
  • 字符串復制
s1 = hello
s2 = s1 # s2 = ‘hello‘
 
若指定長度
s1 = hello
s2 = s1[0:2] #s2 = ‘he‘
  • 字符串連接
s1 = hello
s2 = world
s3 = s1 + s2  #s3 = ‘helloworld‘
 
或者
import operator
s3 = operator.concat(s1,s2) #
concat為字符串拼接函數
  • 字符串比較
(1)利用operator模塊方法比較(python3.X取消了cmd函數)
包含的方法有:
lt(a, b) ———— 小於
le(a, b) ———— 小於等於
eq(a, b) ———— 等於
ne(a, b) ———— 不等於
ge(a, b) ———— 大於等於
gt(a, b) ———— 大於
 
例子:
>>>import operator
>>>operator.eq(abc,edf) #根據ASCII碼比較
Flase
>>>operator.gt(abc
,ab) True (2)關系運算符比較(>,<,>=,<=,==,!=>>>s1 = abc >>>s2 = ab >>>s1 > s2 True >>>s1 == s2 False
  • 求字符串長度
>>>s1 = hello
>>>len(s1)
5
  • 求字符串中最大字符,最小字符
>>>s1 = hello
>>>max(s1) #求字符串s1中最大字符
o
>>>min(s1) #求字符串s2中最小字符
e
  • 字符串大小寫轉換
主要有如下方法:
upper ———— 轉換為大寫
lower ———— 轉換為小寫
title ———— 轉換為標題(每個單詞首字母大寫)
capitalize ———— 首字母大寫
swapcase ———— 大寫變小寫,小寫變大寫
 
例子:
>>>s1 = hello
>>>s2 = WORLD
>>>s3 = hello world
>>>s1.upper() 
HELLO
>>>s2.lower() 
world
>>>s3.title()  
Hello World
>>>s3.capitalize() 
Hello world
>>>s3.title().swapcase() 
hELLO wORLD
  • 字符串翻轉
>>>s1 = hello
>>>s1[::-1]
olleh
  • 字符串分割
split方法,根據參數進行分割,返回一個列表

例子:
>>>s1 = hello,world >>>s1.split(,) [hello,world]
  • 字符串序列連接
join方法:
    語法為str.join(seq) #seq為元素序列
 
例子:
 
>>>l = [hello,world]
>>>str = -
>>>str.join(l)
hello-world
  • 字符串內查找
find方法:
檢測字符串內是否包含子串str
語法為:
    str.find(str[,start,end]) #str為要查找的字符串;strat為查找起始位置,默認為0;end為查找終止位置,默認為字符串長度。若找到返回起始位置索引,否則返回-1
 
例子:
 
>>>s1 = today is a fine day
>>>s1.find(is)
6
>>>s1.find(is,3)
6
>>>s1.find(is,7,10)
-1
  • 字符串內替換
replace方法:
把字符串中的舊串替換成新串
語法為:
    str.replace(old,new[,max]) #old為舊串,new為新串,max可選,為替換次數
 
例子:
>>>s1 = today is a find day
>>>s1.replace(find,rainy)
today is a rainy day
  • 判斷字符串組成
主要有如下方法:
isdigit ———— 檢測字符串時候只由數字組成
isalnum ———— 檢測字符串是否只由數字和字母組成
isalpha ———— 檢測字符串是否只由字母組成
islower ———— 檢測字符串是否只含有小寫字母
isupper ———— 檢測字符串是否只含有大寫字母
isspace ———— 檢測字符串是否只含有空格
istitle ———— 檢測字符串是否是標題(每個單詞首字母大寫)
 
例子:
>>>s1  = hello
>>>s1.islower()
True
>>>s1.isdigit()
False

python3字符串操作總結