字符串格式化:
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'