Python字符串經常使用處理函數

代碼運行 python 版本 3.7python

index() 獲取子串在字符串中出現的位置索引值

lang = 'aaa1113234'
lang.index('a')
# 0
lang.index('1')
# 3
lang.index('23')
# 7

使用索引獲取單字符

索引0爲第一字符。索引可爲負數,表示從尾部(右側)起始編程

lang = 'python'
lang1 = '老陸編程測試中文'
lang[3]
# h
lang1[3]
# 程
lang[-1]
# n
lang1[-1]
# 文

使用切片獲取子串

獲取子串包括首索引字符,不包括尾索引字符api

lang[1:4]
# yth
lang[1:]
# ython
lang[:3]
# pyt
lang[-2:]
# on 注意此處尾索引不能爲0,不然獲得空字符串''
lang[-4:-2]
# th
lang[:-4]
# py
lang[:]
# python

反轉字符串

中文也有效數組

lang1 = '老陸編程測試中文'
lang1[::-1]
# 文中試測程編陸老

len()方法獲取字符串長度

len(lang)
# 6
len(lang1)
# 8

in 操做符判斷子串是否在字符串中

'p' in lang
# True
'ab' in lang
# False
'測試' in lang1
# True

max() 和 min() 獲取字符串中編碼最大和最小的字符

max(lang)
# y
min(lang)
# h
max(lang1)
# 陸
min(lang1)
# 中

操做符 * 對字符串進行重複

lang * 2
# pythonpython
lang1 * 2
# 老陸編程測試中文老陸編程測試中文

使用比較運算符(>、<、<=、>=、!=、==)比較字符串

由於是編碼比較,這種比較用處不大函數

lang > lang1
# False
'F'>'f'
# False

chr() 和 ord() 在字符和編碼間轉化

ord('測')
# 27979
chr(27979)
# 測

str() 將其餘數據類型轉化爲字符串

num = 3.14
str(num)
# 3.14

capitalize() 方法將字符串第一字符變大寫,其餘變小寫

全角英文也有效測試

lang2 = 'p測試K pYthon'
lang2.capitalize()
# P測試k python
lang.capitalize()
# Python

upper()、lower() 函數對字符串中字符轉大寫和小寫

全角英文也有效,全角英文轉換時返回對於的全角大小寫編碼

lang2 = 'p測試K pYthon'
lang2.upper()
# P測試K PYTHON
lang2.lower()
# p測試k python

swapcase() 對字符串中全部字符進行大小寫互換

大寫變小寫,小寫變大寫,中文無效code

lang2 = 'p測試K pYthon'
# P測試k PyTHON

strip()、lstrip() 和 rstrip() 去掉首尾空格、作空格、右空格

'  python   '.strip()
# 'python'
'  python   '.lstrip()
# 'python   '
'  python   '.strip()
# '  python'

split() 方法按指定字符串分割,返回 list

lang2 = 'p測試K pYthon'
lang2.split('K p')
# ['p測試', 'Ython']

jion() 方法連接字符串數組

a = 'hello world'.split()
'|-|'.join(a)
# hello|-|world

find() 方法判斷一個字符串中是否包含子串

三個參數,第一個必須,指定須要搜索的子串,第2、三參數指定搜索起始位置和終止位置,搜索獲得則返回索引值,得不到則返回-1索引

'hello world'.find('llo')
# 2
'hello world'.find('lloe')
# -1

endswith() 和 startswith() 方法判斷一個字符串是否以某個字符串結尾、開頭,參數和find()一致

'hello'.startswith('he')
# True
'hello'.endswith('lo')
# True
'hello'.endswith('le')
# False

count() 方法獲取某個子串在字符串中出現的次數

lang3 = '老陸編程測試字符串統計測試編程'
lang3.count('程')
# 2
lang3.count('測試')
# 2
lang3.count('老陸')
# 1

isupper()、islower()判斷字符串中字符是否都是大、小寫

若是字符串中有中文,中文會被忽略只判斷字符串中的英文,若是字符串中全是中文則這兩個方法都返回False,全角英文也可正常判斷ip

'Y測試K'.isupper()
# True
'Y測試k'.isupper()
# False

replace(old,new) 用字符串new替換字符串中的子串old

'這是測試old子串'.replace('old', 'new')
# 這是測試new子串
相關文章
相關標籤/搜索