Python字元串常用處理函數
代碼運行 python 版本 3.7
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]
# 文
使用切片獲取子串
獲取子串包括首索引字元,不包括尾索引字元
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() 對字元串中所有字元進行大小寫互換
大寫變小寫,小寫變大寫,中文無效
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() 方法判斷一個字元串中是否包含子串
三個參數,第一個必須,指定需要搜索的子串,第二、三參數指定搜索起始位置和終止位置,搜索得到則返回索引值,得不到則返回-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,全形英文也可正常判斷
"Y測試K".isupper()
# True
"Y測試k".isupper()
# False
{!-- PGC_COLUMN --}
? 著作權歸作者所有
作者:編程老陸
原文:https://my.oschina.net/u/2357619/blog/3006226
![](https://pic.pimg.tw/zzuyanan/1488615166-1259157397.png)
![](https://pic.pimg.tw/zzuyanan/1482887990-2595557020.jpg)
TAG:程序員小新人學習 |