字符串格式化:
str='python String function'
字符串長度獲取:len(str)
例:print '%s length= %d' % (str,len(str))
1. 打印字符串
print ("His name is %s"%("Aviad"))
效果:
2.打印整數
print ("He is %d years old"%(25))
效果:
3.打印浮點數
print ("His height is %f m"%(1.83))
效果:
4.打印浮點數(指定保留小數點位數)
print ("His height is %.2f m"%(1.83))
效果:
5.指定佔位符寬度
print ("Name:%10s Age:%8d Height:%8.2f"%("Aviad",25,1.83))
效果:
6.指定佔位符寬度(左對齊)
print ("Name:%-10s Age:%-8d Height:%-8.2f"%("Aviad",25,1.83))
效果:
7.指定佔位符(只能用0當佔位符?)
print ("Name:%-10s Age:%08d Height:%08.2f"%("Aviad",25,1.83))
效果:
8.科學計數法
format(0.0015,'.2e')
效果:
字母和字符串之間轉換:
>>>
ord('A')
65
>>>
chr(65)
'A'
編碼解碼:
Unicode用utf-8來編碼
>>> u'中文'.encode('utf-8')
'\xe4\xb8\xad\xe6\x96\x87'
把utf-8編碼的字符串按照utf-8的編碼方式進行解碼成 Unicode
>>> print '\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
中文
#!/usr/bin/env python
# -*- coding: utf-8 -*-
第一行註釋是爲了告訴Linux/OS X系統,這是一個Python可執行程序,Windows系統會忽略這個註釋;
第二行註釋是爲了告訴Python解釋器,按照UTF-8編碼讀取源代碼,否則,你在源代碼中寫的中文輸出可能會有亂碼。
字母大小寫
全部大寫:str.upper()
全部小寫:str.lower()
大寫轉小寫,小寫轉大寫:str.swapcase()
第一個字母大寫,其餘小寫:str.capitalize()
每個單詞首字母大寫:str.title() #以非字母進行單詞分割
>>> str='python StringFunction'
>>> str.capitalize()
'Python string function'
>>> str="aaaa11bbbb and,his! is [a man]"
>>> str.title() #以非字母進行單詞分割 單詞首字符變成大寫,其他變成小寫。
'Aaaa11Bbbb And,His! Is [A Man]'
字符串判斷相關
是否以start開頭:str.startswith('start')
是否以end結尾:str.endswith('end')
是否全爲字母或數字:str.isalnum()
是否全字母:str.isalpha()
是否全數字:str.isdigit()
是否全小寫:str.islower()
是否全大寫:str.isupper()
是否單詞首字母大寫:str.istitle()
是否全爲空白字符:str.isspace()
>>> a='\r\t\n'
>>> a.isspace()
True
字符串搜索相關
搜索指定字符串,沒有返回-1:str.find('t')
指定起始位置搜索:str.find('t',start)
指定起始及結束位置搜索:str.find('t',start,end)#不包含end
從右邊開始查找:str.rfind('t')
搜索到多少個指定字符串:str.count('t')
指定起始搜索位置:str.count(‘t’,start)
指定起始以結束搜索位置:str.count(‘t’,start.,end)#不包含end
以上find所有方法都可用index代替,不同的是index查找不到會拋異常,而find返回-1
>>> a="aabbaaaabbb"
>>> a.count('a',5,8)
3
>>> a.count('a',5,6)
1
字符串替換相關
替換old爲new:str.replace('old','new')
替換指定次數的old爲new:str.replace('old','new',maxReplaceTimes)
>>> a="aabbaaaabbb"
>>> a.replace('a','!')
'!!bb!!!!bbb'
>>> a.replace('a','!',2)
'!!bbaaaabbb'
>>>
字符串去空格,去指定字符以及分割和連接
去兩邊空格:str.strip()#直到兩邊是非空格
去左空格:str.lstrip()
去右空格:str.rstrip()
去兩邊字符串:str.strip('d')#直到首字符和尾字符非‘d’
去左字符:str.lstrip(‘d’)
去右字符:str.rstrip(‘d’)
分割字符串:str.split(' ',maxtime)
連接字符串:str.join(‘abcde’)
#將str插入到參數“abcde”的每兩個字符中,如果參數字符只有一個字符,只返回參數字符
>>> a="sssq aaa bbb ccc qsss"
>>> a.strip('s')
'q aaa bbb ccc q'
>>> a.split(' ',2)
['sssq', 'aaa', 'bbb ccc qsss']
>>> a='sss'
>>> a.join('!!')
'!sss!'
>>> a.join('!')
'!'
>>>
補全:
獲取固定長度,左對齊,左邊不夠用空格補齊:str.ljust(width)
獲取固定長度,右對齊,右邊不夠用空格補齊:str.rjust(width)
獲取固定長度,中間對齊,兩邊不夠用空格補齊:str.center(width)
獲取固定長度,右對齊,左邊不足用0補齊:str.zfill(width)
>>> a='aaa'
>>> a.ljust(20)
'aaa '
>>> a.zfill(20)
'00000000000000000aaa'