歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python字符串str的方法使用

Python字符串str的方法使用

日期:2017/3/1 9:09:32   编辑:Linux編程

#!usr/bin/env python
# -*-coding:utf-8-*-
#字符串通常用雙引號或單引號來表示:'123',"abc","字符串"
#str字符串的常用方法有以下:字符串可以用於賦值臨時變量s
#友情提示以下全是python2.x版本演示,python3.x請在print(放入測試打印),例如:print(len(s))
from string import maketrans
s3 = '123'
s2 = ' '
s1 = 'This Is \t Cash'
s='abcdefghijklmnopqrstuvwxyz'
s4 = "0000000this is string example....wow!!!0000000"
s5 = 'ab c\n\nde fg\rkl\r\n'
print s[0:6] #切片,截取字符串中的一段(以下標的起始位置到結束位置)
print len(s) #統計字符串的長度
print s.ljust(50,'0'),'--->ljust方法' #返回一個原字符串右用字符串0填充左對齊並寬度50的新字符串
print s.rjust(50,'0'),'--->rjust方法' #返回一個原字符串左用字符串0填充右對齊並寬度50的新字符串
print s.capitalize(),'--->capitalize方法' #返回字符串首字母大寫的副本
print s.center(50,'*'),'--->center方法' #表示原字符串居中兩邊填充寬度的用法
print format(s, '.3'),'--->format方法' #格式化輸出也可當切片用的方式
print s.upper(),'--->upper方法' #將小寫字母轉換成大寫字母
print s.lower(),'--->lower方法' #將大寫字母轉換成小寫字母
print s3.isdigit(),'--->isdigit方法' #判斷字符串如果是數字返回真True,不是返回假False
print s.startswith('abc'),'--->startswith方法' #判斷字符串是否是以abc開頭如果是返回真,否則返回假
print s.endswith('zz'),'--->endswith方法' #判斷字符串是否以yz結尾是返回真,否則返回假
print s1.expandtabs(),'--->expandtabs方法' #把字符串中的 tab 符號('\t')轉為空格,tab 符號('\t')默認的空格數是8
print s.isalnum(),'--->isalnum方法' #判斷字符串至少有一個字符並且所有字符都是字母或數字則返回 True,否則返回 False
print s.isalpha(),'--->isalpha方法' #判斷字符串至少有一個字符並且所有字符都是字母則返回 True,否則返回 False
print s2.isspace(),'--->isspace方法' #判斷字符串中只包含空格,則返回 True,否則返回 False
print s1.istitle(),'--->istitle方法' #如果字符串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫則返回 True,否則返回 False
print s4.strip("0"),'--->strip方法' #返回移除字符串頭尾指定的字符生成的新字符串
print s.find('sd'),'--->find方法' #檢查是否包含在指定范圍內,如果包含子字符串返回開始的索引值,否則返回-1。
print s.index('s'),'--->index方法' #檢查是否包含在指定范圍內,該方法與find()方法一樣,只不過如果不在字符串中會報一個異常
print s.partition("k"),'--->partition方法' #生成一個分隔符k,第一個為分隔符左邊的子串,第二個為分隔符本身,第三個為分隔符右邊的子串。
print s1.swapcase(),'--->swapcase方法' #返回大小寫字母轉換後生成的新字符串
print s5.splitlines(),'--->splitlines方法' #返回一個包含各行作為元素的列表
print s2.join(s3),'--->join方法' #返回通過指定字符連接序列中元素後生成的新字符串
print s3.translate(maketrans(s3,s2)) #返回翻譯後的字符串(有點復雜)自信百度補腦
print s3.zfill(10),'--->zfill方法' #返回指定寬度的字符串原字符串右對齊,前面填充0
#以下打印輸出:

零基礎如何入門Python http://www.linuxidc.com/Linux/2016-10/136485.htm

Ubuntu 14.04安裝Python 3.3.5 http://www.linuxidc.com/Linux/2014-05/101481.htm

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

在CentOS 6.5上安裝Python2.7 http://www.linuxidc.com/Linux/2016-10/136206.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Copyright © Linux教程網 All Rights Reserved