python中提供了豐富的字符串處理函數,很多都可以以不同方式處理大小寫的轉換
常用的有這些
# 我多敲了好多回車...只是爲了看得清楚一點
>>> notMe = 'lapland Stark is an elf'
>>> print("source string is ", notMe)
source string is lapland Stark is an elf
>>>
>>> print("swapcase demo", notMe.swapcase(), sep='\t')
swapcase demo LAPLAND sTARK IS AN ELF
>>>
>>> print("upper demo", notMe.upper(), sep='\t')
upper demo LAPLAND STARK IS AN ELF
>>>
>>> print("lower demo", notMe.lower(), sep='\t')
lower demo lapland stark is an elf
>>>
>>> print("title demo", notMe.title(), sep='\t')
title demo Lapland Stark Is An Elf
>>>
>>> print("istitle demo", notMe.istitle(), sep='\t')
istitle demo False
>>>
>>> print("islower demo", notMe.islower(), sep='\t')
islower demo False
>>>
>>> print("capitalize demo", notMe.capitalize(), sep='\t')
capitalize demo Lapland stark is an elf
>>>
>>> print("find demo", notMe.find('r'), sep='\t')
find demo 11
>>>
>>> print("count demo", notMe.count('l'), sep='\t')
count demo 3
>>>
>>> print("split demo", notMe.split(' '), sep='\t')
split demo ['lapland', 'Stark', 'is', 'an', 'elf']
>>>
>>> print("join demo", '.'.join(notMe), sep='\t')
join demo l.a.p.l.a.n.d. .S.t.a.r.k. .i.s. .a.n. .e.l.f
>>>
>>> print("len demo", len(notMe), sep='\t')
len demo 23
大致分類如下:
- 長度
字符串長度獲取:len(str)
- 字母處理
- 全部大寫:
str.upper()
- 全部小寫:
str.lower()
- 大小寫互換:
str.swapcase()
- 首字母大寫,其餘小寫:
str.capitalize()
- 首字母大寫:
str.title()
- 格式化相關
- 獲取固定長度,右對齊,左邊不夠用空格補齊:
str.ljust(width)
- 獲取固定長度,左對齊,右邊不夠用空格補齊:
str.ljust(width)
- 獲取固定長度,中間對齊,兩邊不夠用空格補齊:
str.ljust(width)
- 獲取固定長度,右對齊,左邊不足用0補齊
- 字符串搜索相關
- 搜索指定字符串,沒有返回-1:
str.find(‘t’)
- 指定起始位置搜索:
str.find(‘t’,start)
- 指定起始及結束位置搜索:
str.find(‘t’,start,end)
- 從右邊開始查找:
str.rfind(‘t’)
- 搜索到多少個指定字符串:
str.count(‘t’)
- 上面所有方法都可用index代替,不同的是使用index查找不到會拋異常,而find返回-1
- 字符串替換相關
- 替換old爲new:
str.replace(‘old’,’new’)
- 替換指定次數的old爲new:
str.replace(‘old’,’new’,maxReplaceTimes)
- 字符串去空格及去指定字符
- 去兩邊空格:
str.strip()
- 去左空格:
str.lstrip()
- 去右空格:
str.rstrip()
- 去兩邊字符串:
str.strip(‘d’)
,相應的也有lstrip,rstrip - 按指定字符分割字符串爲數組:
str.split(' ')
(默認按空格分隔)
- 字符串判斷相關
- 是否以start開頭:
str.startswith(‘start’)
- 是否以end結尾:
str.endswith(‘end’)
- 是否全爲字母或數字:
str.isalnum()
- 是否全字母:
str.isalpha()
- 是否全數字:
str.isdigit()
- 是否全小寫:
str.islower()
- 是否全大寫:
str.isupper()