文档库 最新最全的文档下载
当前位置:文档库 › python字符串内置函数

python字符串内置函数

python字符串内置函数
python字符串内置函数

a='helLO'

print(a.title()) # 首字母大写a='1 2'

执行结果:1 2 1 2 1 2 00000001 2

1

2

3

4

5

6

7

8

# 3 字符串搜索相关

.find() # 搜索指定字符串,没有返回-1

.index() # 同上,但是找不到会报错

.rfind() # 从右边开始查找

.count() # 统计指定的字符串出现的次数

# 上面所有方法都可以用index代替,不同的是使用index查找不到会抛异常,而find s='hello world'

print(s.find('e')) # 搜索指定字符串,没有返回-1

print(s.find('w',1,2)) # 顾头不顾尾,找不到则返回-1不会报错,找到了

则显示索引

print(s.index('w',1,2)) # 同上,但是找不到会报错

print(s.count('o')) # 统计指定的字符串出现的次数

print(s.rfind('l')) # 从右边开始查找

# 4字符串替换

.replace('old','new') # 替换old为new

.replace('old','new',次数) # 替换指定次数的old为new

s='hello world'

print(s.replace('world','python'))

print(s.replace('l','p',2))

print(s.replace('l','p',5))

执行结果:

hello python

heppo world

heppo worpd

# 5字符串去空格及去指定字符

.strip() # 去两边空格

.lstrip() # 去左边空格

.rstrip() # 去右边空格

.split() # 默认按空格分隔

.split('指定字符') # 按指定字符分割字符串为数组

s=' h e-l lo '

print(s)

print(s.strip())

print(s.lstrip())

print(s.rstrip())

print(s.split('-'))

print(s.split())

# 6字符串判断相关

.startswith('start') # 是否以start开头

.endswith('end') # 是否以end结尾

.isalnum() # 是否全为字母或数字

.isalpha() # 是否全字母

.isdigit() # 是否全数字

.islower() # 是否全小写

.isupper() # 是否全大写

.istitle() # 判断首字母是否为大写

.isspace() # 判断字符是否为空格

# 补充

bin() # 十进制数转八进制

hex() # 十进制数转十六进制

range() # 函数:可以生成一个整数序列

type() # 查看数据类型

len() # 计算字符串长度

format() # 格式化字符串,类似%s,传递值能多不能少

4、内置函数

? 数学运算(7个)

? 类型转换(24个)

? 序列操作(8个)

? 对象操作(7个)

? 反射操作(8个)

? 变量操作(2个)

? 交互操作(2个)

? 文件操作(1个)

? 编译执行(4个)

?

装饰器(3个)

补充:

"""

python内置装饰器

在python中有三个内置的装饰器,都是跟class相关的:staticmethod、classmethod、property.

@staticmethod 是类的静态方法,其跟成员方法的区别是没有self参数,并且可以在类不进行实例化的情况下调用

@classmethod 与成员方法的区别在于所接收的第一个参数不是self(类实例的指针),而是cls(当前类的具体类型)

@property 是属性的意思,表示可以通过类实例直接访问的信息

"""

class Foo(object):

def__init__(self,var):

super(Foo,self).__init__()

self._var=var

@property

def var(self):

return self._var

@var.setter

def var(self,var):

self._var=var

f=Foo('var1')

print(f.var)

f.var='var2'

print(f.var)

"""

注意,对于Python新式类(new-style class),如果将上面的

“@var.setter” 装饰器所装饰的成员函数去掉,

则Foo.var 属性为只读属性,使用“foo.var = ‘var 2′” 进行赋值时会抛出异常。

但是,对于Python classic class,所声明的属性不是 read-only的,所以即使去掉”@var.setter”装饰器也不会报错。

"""

python考试复习题库

一、填空题 1、Python安装扩展库常用的是_工具。(pip) 2、Python标准库math中用来计算平方根的函数是____。(sqrt) 3、Python程序文件扩展名主要有__和两种,其中后者常用于GUI程序。(py、pyw) 4、Python源代码程序编译后的文件扩展名为___。(pyc) 5、使用pip工具升级科学计算扩展库numpy的完整命令是_______。(pip install –upgrade numpy) 6、使用pip工具查看当前已安装的Python扩展库的完整命令是___。(pip list) 7、在IDLE交互模式中浏览上一条语句的快捷键是____。(Alt+P) 8、使用pip工具查看当前已安装Python扩展库列表的完整命令是___。(pip list) 9、在Python中____表示空类型。(None) 10、列表、元组、字符串是Python的___(有序?无序)序列。(有序) 11、查看变量类型的Python内置函数是______。(type()) 12、查看变量内存地址的Python内置函数是_______。(id()) 13、以3为实部4为虚部,Python复数的表达形式为_或__。(3+4j、3+4J) 14、Python运算符中用来计算整商的是___。(//) 15、Python运算符中用来计算集合并集的是_。(|) 16、使用运算符测试集合包含集合A是否为集合B的真子集的表达式可以写作_。(A < B ) 17、表达式[1, 2, 3]*3的执行结果为____________。([1, 2, 3, 1, 2, 3, 1, 2, 3]) 18、list(map(str, [1, 2, 3]))的执行结果为___________。([‘1’, ‘2’, ‘3’]) 19、语句x = 3==3, 5执行结束后,变量x的值为___。((True, 5)) 20、已知x = 3,那么执行语句x += 6 之后,x的值为_____。(9) 21、已知x = 3,并且id(x)的返回值为496103280,那么执行语句x += 6 之后,表达式id(x) == 496103280 的值为_。(False) 22、已知x = 3,那么执行语句x *= 6 之后,x的值为______。(18) 23、为了提高Python代码运行速度和进行适当的保密,可以将Python程序文件编译为扩展名____的文件。(pyc) 24、表达式“[3] in [1, 2, 3, 4]”的值为______。(False) 25、列表对象的sort()方法用来对列表元素进行原地排序,该函数返回值为。(None) 26、假设列表对象aList的值为[3, 4, 5, 6, 7, 9, 11, 13, 15, 17],那么切片aList[3:7]得到的值是____________。([6, 7, 9, 11]) 27、使用列表推导式生成包含10个数字5的列表,语句可以写为_____。([5 for i in range(10)]) 28、假设有列表a = [‘name’, ‘age’, ‘sex’]和b = [‘Dong’, 38, ‘Male’],请使用一个语句将这两个列表的内容转换为字典,并且以列表a中的元素为“键”,以列表b中的元素为“值”,这个语句可以写为___________。(c = dict(zip(a, b))) 29、任意长度的Python列表、元组和字符串中最后一个元素的下标为__。(-1) 30、Python语句”.join(list(‘hello world!’))执行的结果是__________。(’hello world!’) 31、转义字符’\n’的含义是_________。(回车换行) 32、Python语句list(range(1,10,3))执行结果为_________。([1, 4, 7]) 33、表达式list(range(5)) 的值为______。([0, 1, 2, 3, 4]) 34、____命令既可以删除列表中的一个元素,也可以删除整个列表。(del) 35、已知a = [1, 2, 3]和b = [1, 2, 4],那么id(a[1])==id(b[1])的执行结果为_。(True) 36、表达式int(‘123’, 16) 的值为___。(291) 37、表达式int(‘123’, 8) 的值为___。(83) 38、表达式int(‘123’) 的值为___。(123) 39、表达式int(‘101’,2) 的值为____。(5) 40、表达式abs(-3) 的值为_。(3)

Python常用内置函数总结

Python常用内置函数总结 一、数学相关 1、绝对值:abs(-1) 2、最大最小值:max([1,2,3])、min([1,2,3]) 3、序列长度:len('abc')、len([1,2,3])、len((1,2,3)) 4、取模:divmod(5,2)//(2,1) 5、乘方:pow(2,3,4)//2**3/4 6、浮点数:round(1)//1.0 二、功能相关 1、函数是否可调用:callable(funcname),注意,funcname变量要定义过 2、类型判断:isinstance(x,list/int) 3、比较:cmp('hello','hello') 4、快速生成序列:(x)range([start,] stop[, step]) 三、类型转换 1、int(x) 2、long(x) 3、float(x) 4、complex(x) //复数 5、str(x) 6、list(x) 7、tuple(x) //元组 8、hex(x) 9、oct(x) 10、chr(x)//返回x对应的字符,如chr(65)返回‘A' 11、ord(x)//返回字符对应的ASC码数字编号,如ord('A')返回65 四、字符串处理 1、首字母大写:str.capitalize 复制代码代码如下:

>>> 'hello'.capitalize() 'Hello' 2、字符串替换:str.replace 复制代码代码如下: >>> 'hello'.replace('l','2') 'he22o' 可以传三个参数,第三个参数为替换次数 3、字符串切割:str.split 复制代码代码如下: >>> 'hello'.split('l') ['he', '', 'o'] 可以传二个参数,第二个参数为切割次数 以上三个方法都可以引入String模块,然后用string.xxx的方式进行调用。 五、序列处理函数 1、len:序列长度 2、max:序列中最大值 3、min:最小值 4、filter:过滤序列 复制代码代码如下: >>> filter(lambda x:x%2==0, [1,2,3,4,5,6]) [2, 4, 6] 5、zip:并行遍历 复制代码代码如下:

python函数中文手册

内置函数 一,文档说明 原始文档来自于python v2.7.2 中文译文和用法尚不完全,您可以自由修改和完善, 您可以在文档结尾鸣谢添上您的名字,我们将会感谢您做的贡献! 二,函数列表 1,取绝对值 abs(x)

Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned. 如果你不知道绝对值什么意思,那就要补一下小学数学了! 基本用法 2, all(iterable) Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to: 3. any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to: 4. basestring() This abstract type is the superclass for str and unicode. It cannot be called or instantiated, but it can be used to test whether an object is an instance of str or unicode. isinstance(obj, basestring) is equivalent to isinstance(obj, (str, unicode)). 是字符串和字符编码的超类,是抽象类型。不能被调用或者实例化。可以用来判断实例是否为字符串或者字符编码。 方法: 5.二进制转换 bin(x) Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

Python基本操作题

1.请补充横线处的代码,让Python 帮你随机选一个饮品吧! import ____①____ (1) listC = ['加多宝','雪碧','可乐','勇闯天涯','椰子汁'] print(random. ____②____ (listC)) 参考答案: import random (1) listC = ['加多宝','雪碧','可乐','勇闯天涯','椰子汁'] print(listC)) 2.请补充横线处的代码,listA中存放了已点的餐单,让Python帮你增加一个“红烧肉”,去掉一个“水煮干丝”。 listA = ['水煮干丝','平桥豆腐','白灼虾','香菇青菜','西红柿鸡蛋汤'] listA. ____①____ ("红烧肉") ②____ ("水煮干丝") print(listA) 参考代码: listA = ['水煮干丝','平桥豆腐','白灼虾','香菇青菜','西红柿鸡蛋汤'] ("红烧肉") ("水煮干丝") print(listA) 3.请补充横线处的代码。dictMenu中存放了你的双人下午套餐(包括咖啡2份和点心2份)的价格,让Python帮忙计算并输出消费总额。 dictMenu = {'卡布奇洛':32,'摩卡':30,'抹茶蛋糕':28,'布朗尼':26} ___①____ for i in ____②____: sum += i print(sum) 参考代码: dictMenu = {'卡布奇洛':32,'摩卡':30,'抹茶蛋糕':28,'布朗尼':26} sum = 0 for i in (): sum += i print(sum) 4.获得输入正整数 N,反转输出该正整数,不考虑异常情况。 参考代码: N = input() print(N[::-1]) 5. 给定一个数字123456,请采用宽度为25、右对齐方式打印输出,使用加号“+”填充。 参考代码: print("{:+>25}".format(123456)) 6.给定一个数字.9,请增加千位分隔符号,设置宽度为30、右对齐方式打印输出,使用空格填充。 参考代码:

Python3 常用函数

Python3 常用函数.笔记 Python 3自学.笔记 type()检查变量数据: >>> x = 10 >>> type(x) (cla ss ‘int’) exit( ) 执行到此命令时,程序终止:!!! >>> a = 0 >>> w hile a < 20: a = a + 1 if a == 5: else:#执行到此命令时,程序终止 a = 100 >>> print(a) 5 abs()返回一个数的绝对值: >>> abs(3) 3 >>> abs(-3) 3 while _ _ _ : 循环执行程序: >>> n = 0 >>> w hile n < 3:#(a n d/o r/n o t) n = n + 1 print(n) Continue 继续下一轮循环 Break 退出整个循环 round()对小数进行四舍五入操作: >>> x = 3.1415926 >>> round(x , 2) #保留2位小数

3.14 for _ _ _ in _ _ _ : 可以遍历任何序列的项目(如一个列表或者一个字符串): >>> s = 'a bc def123456' >>> for i in s: print(i) a b c d ...... range( ) 返回一个可迭代对象: >>> range(20) range(0, 20) #默认以0开始 >>> a = 20 >>> for i in ra nge(0 , a , 5): #步长为:5(默认步长为1)print(i) 5 10 15 #计数到20但不包括20 >>> break 退出整个循环: >>> i = 0 >>> w hile i < 10: i = i + 1 if i == 5: Break #执行到此时退出循环结构 >>> print(i) 5 字符串:

python字符串内置函数

a='helLO' print(a.title()) # 首字母大写a='1 2'

执行结果:1 2 1 2 1 2 00000001 2 1 2 3 4 5 6 7 8 # 3 字符串搜索相关 .find() # 搜索指定字符串,没有返回-1 .index() # 同上,但是找不到会报错 .rfind() # 从右边开始查找 .count() # 统计指定的字符串出现的次数 # 上面所有方法都可以用index代替,不同的是使用index查找不到会抛异常,而find s='hello world' print(s.find('e')) # 搜索指定字符串,没有返回-1 print(s.find('w',1,2)) # 顾头不顾尾,找不到则返回-1不会报错,找到了 则显示索引 print(s.index('w',1,2)) # 同上,但是找不到会报错 print(s.count('o')) # 统计指定的字符串出现的次数 print(s.rfind('l')) # 从右边开始查找 # 4字符串替换 .replace('old','new') # 替换old为new .replace('old','new',次数) # 替换指定次数的old为new s='hello world' print(s.replace('world','python')) print(s.replace('l','p',2)) print(s.replace('l','p',5)) 执行结果: hello python heppo world heppo worpd

# 5字符串去空格及去指定字符 .strip() # 去两边空格 .lstrip() # 去左边空格 .rstrip() # 去右边空格 .split() # 默认按空格分隔 .split('指定字符') # 按指定字符分割字符串为数组 s=' h e-l lo ' print(s) print(s.strip()) print(s.lstrip()) print(s.rstrip()) print(s.split('-')) print(s.split()) # 6字符串判断相关 .startswith('start') # 是否以start开头 .endswith('end') # 是否以end结尾 .isalnum() # 是否全为字母或数字 .isalpha() # 是否全字母 .isdigit() # 是否全数字 .islower() # 是否全小写 .isupper() # 是否全大写 .istitle() # 判断首字母是否为大写 .isspace() # 判断字符是否为空格 # 补充 bin() # 十进制数转八进制 hex() # 十进制数转十六进制 range() # 函数:可以生成一个整数序列 type() # 查看数据类型 len() # 计算字符串长度 format() # 格式化字符串,类似%s,传递值能多不能少

最新python常用函数资料

1.map()函数map()是Python 内置的高阶函数,它接收一个函数f和一个list,并通过把函数 f 依次作用在list 的每个元素上,得到一个新的list 并返回。 例如,对于list [1, 2, 3, 4, 5, 6, 7, 8, 9] 如果希望把list的每个元素都作平方,就可以用map()函数: 因此,我们只需要传入函数f(x)=x*x,就可以利用map()函数完成这个计算: def f(x): return x*x print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) 输出结果: [1, 4, 9, 10, 25, 36, 49, 64, 81] 可以用列表替代 注意:map()函数不改变原有的list,而是返回一个新的list。

利用map()函数,可以把一个list 转换为另一个list,只需要传入转换函数。 由于list包含的元素可以是任何类型,因此,map() 不仅仅可以处理只包含数值的list,事实上它可以处理包含任意类型的list,只要传入的函数f可以处理这种数据类型。 假设用户输入的英文名字不规范,没有按照首字母大写,后续字母小写的规则,请利用map()函数,把一个list(包含若干不规范的英文名字)变成一个包含规范英文名字的list: 输入:['adam', 'LISA', 'barT'] 输出:['Adam', 'Lisa', 'Bart'] format_name(s)函数接收一个字符串,并且要返回格式化后的字符串,利用map()函数,就可以输出新的list。 参考代码: def format_name(s): return s[0].upper() + s[1:].lower() print map(format_name, ['adam', 'LISA', 'barT']) 2.reduce()函数 reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和map()类似,一个函数f,一个list,但行为和map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list 的每个元素反复调用函数f,并返回最终结果值。 例如,编写一个f函数,接收x和y,返回x和y的和: def f(x, y): return x + y 调用reduce(f, [1, 3, 5, 7, 9])时,reduce函数将做如下计算:

python3内置函数大全

一、数学相关 1、绝对值:abs(-1) 2、最大最小值:max([1,2,3])、min([1,2,3]) 3、序列长度:len('abc')、len([1,2,3])、len((1,2,3)) 4、取模:divmod(5,2)//(2,1) 5、乘方:pow(2,3,4)//2**3/4 6、浮点数:round(1)//1.0 二、功能相关 1、函数是否可调用:callable(funcname),注意,funcname变量要定义过 2、类型判断:isinstance(x,list/int) 3、比较:cmp('hello','hello') 4、快速生成序列:(x)range([start,] stop[, step]) 三、类型转换 1、int(x) 2、long(x) 3、float(x) 4、complex(x) //复数 5、str(x) 6、list(x) 7、tuple(x) //元组 8、hex(x) 9、oct(x)

10、chr(x)//返回x对应的字符,如chr(65)返回‘A' 11、ord(x)//返回字符对应的ASC码数字编号,如ord('A')返回65 四、字符串处理 1、首字母大写:str.capitalize 复制代码代码如下: >>> 'hello'.capitalize() 'Hello' 2、字符串替换:str.replace 代码如下: >>> 'hello'.replace('l','2') 'he22o' 可以传三个参数,第三个参数为替换次数 3、字符串切割:str.split 代码如下: >>> 'hello'.split('l') ['he', '', 'o']

Python 的内置字符串方法

字符串处理是非常常用的技能,但Python 内置字符串方法太多,常常遗忘,为了便于快速参考,特地依据Python 3.5.1 给每个内置方法写了示例并进行了归类,便于大家索引。 PS: 可以点击概览内的绿色标题进入相应分类或者通过右侧边栏文章目录快速索引相应方法。 概览 字符串大小写转换 ?str.capitalize() ?str.lower() ?str.casefold() ?str.swapcase() ?str.title() ?str.upper() 字符串格式输出 ?str.center(width[, fillchar]) ?str.ljust(width[, fillchar]); str.rjust(width[, fillchar]) ?str.zfill(width) ?str.expandtabs(tabsize=8)

?str.format(^args, ^^kwargs) ?str.format_map(mapping) 字符串搜索定位与替换 ?str.count(sub[, start[, end]]) ?str.find(sub[, start[, end]]); str.rfind(sub[, start[, end]]) ?str.index(sub[, start[, end]]); str.rindex(sub[, start[, end]]) ?str.replace(old, new[, count]) ?str.lstrip([chars]); str.rstrip([chars]); str.strip([chars]) ?static str.maketrans(x[, y[, z]]); str.translate(table) 字符串的联合与分割 ?str.join(iterable) ?str.partition(sep); str.rpartition(sep) ?str.split(sep=None, maxsplit=-1); str.rsplit(sep=None, maxsplit=-1) ?str.splitlines([keepends]) 字符串条件判断 ?str.endswith(suffix[, start[, end]]); str.startswith(prefix[, start[, end]]) ?str.isalnum() ?str.isalpha() ?str.isdecimal(); str.isdigit(); str.isnumeric() ?str.isidentifier()

python常用函数年初大总结

1.常用内置函数:(不用import就可以直接使用) help(obj) 在线帮助, obj可是任何类型 callable(obj) 查看一个obj是不是可以像函数一样调用 repr(obj) 得到obj的表示字符串,可以利用这个字符串eval重建该对象的一个拷贝 eval_r(str) 表示合法的python表达式,返回这个表达式 dir(obj) 查看obj的name space中可见的name hasattr(obj,name) 查看一个obj的name space中是否有name getattr(obj,name) 得到一个obj的name space中的一个name setattr(obj,name,value) 为一个obj的name space中的一个name指向vale这个object delattr(obj,name) 从obj的name space中删除一个name vars(obj) 返回一个object的name space。用dictionary表示 locals() 返回一个局部name space,用dictionary表示 globals() 返回一个全局name space,用dictionary表示 type(obj) 查看一个obj的类型 isinstance(obj,cls) 查看obj是不是cls的instance issubclass(subcls,supcls) 查看subcls是不是supcls的子类 类型转换函数 chr(i) 把一个ASCII数值,变成字符 ord(i) 把一个字符或者unicode字符,变成ASCII数值 oct(x) 把整数x变成八进制表示的字符串 hex(x) 把整数x变成十六进制表示的字符串

python字符串常用函数

字符串常用函数 replace(string,old,new[,maxsplit]) 字符串的替换函数,把字符串中的old替换成new。默认是把string中所有的old值替换成new 值,如果给出maxsplit值,还可控制替换的个数,如果maxsplit为1,则只替换第一个old 值。 >>>a="11223344" >>>print string.replace(a,"1","one") oneone2223344 >>>print string.replace(a,"1","one",1) one12223344 capitalize(string) 该函数可把字符串的首个字符替换成大字。 >>> import string >>> print string.capitalize("python") Python split(string,sep=None,maxsplit=-1) 从string字符串中返回一个列表,以sep的值为分界符。 >>> import string >>> ip="192.168.3.3" >>> ip_list=string.split(ip,'.') >>> print ip_list ['192', '168', '3', '3'] all( iterable) 如果迭代的所有元素都是真就返回真。 >>> l = [0,1,2,3] >>> all(l) Flase >>> l = [1,2,3] >>> all(l) True any( iterable) 如果迭代中有一个元素为真就返回真。 >>> l = [0,1,2,3] >>> all(l) True >>> l = [1,2,3] >>> all(l) True basestring() 这个抽象类型是str和unicode的父类。它不能被调用或初始化,但是它可以使用来测试一

Python 常用函数

Python 函数 2016年4月14日 22:07 1、join()函数 以下实例展示了join()的使用方法: #!/usr/bin/python str ="-"; seq =("a","b","c");# 字符串序列 print str.join( seq ); 以上实例输出结果如下: a-b-c 2、str.zfill(width) 将字符串str前面补0使得字符串长度为width 3、lambda函数(匿名函数) a. lambda表达式返回可调用的函数对象.但不会把这个函 数对象赋给一个标识符,而def则会把函数对象赋值给一个变 量. https://www.wendangku.net/doc/419228357.html,mbda 它只是一个表达式,而def是一个语句 c.定义一些抽象的,不会别的地方再复用的函数 d. lambda语句中,冒号前是参数,可以有多个,用逗号隔开,冒 号右边的返回值 定义了一个lambda表达式,求三个数的和。 用lambda表达式求n的阶乘。 这里也可以把def直接写成lambda形式。如下 lambda函数可以很好和python中内建filter(),map(),reduce()函数的应用程序结合起来,因为它们都带了一个可执行的函数对象. 4、filter(function or None, sequence) -> list, tuple, or string 给定一个'过滤函数'和一个对象的序列,每个序列元素都通过这个过滤器进行筛选,保留函数返回为真的对象.filter函数为已知的序列的每个元素调用给定布尔函数.每个filter返回的非零(true)值元素添加到一个列表中. 1 2 3 #!/usr/bin/python2.5 from random import randint

python2.72内置函数手册

Python2.72内置函数 1、文档说明 中文译文和用法尚待完善。 2、函数列表 1,取绝对值 abs(x) Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned. 如果你不知道绝对值什么意思,那就要补一下小学数学了! 基本用法 2, all(iterable)

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to: 3. any(iterable) Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to: 4. basestring() This abstract type is the superclass for str and unicode. It cannot be called or instantiated, but it can be used to test whether an object is an instance of str or unicode. isinstance(obj,basestring) is equivalent to isinstance(obj,(str,unicode)). 是字符串和字符编码的超类,是抽象类型。不能被调用或者实例化。可以用来判断实例是否为字符串或者字符编码。 方法: 5.二进制转换 bin(x) Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. 转换成二进制表达 方法: 6.布尔类型 bool([x]) Convert a value to a Boolean, using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. bool is also a class, which is a subclass of int. Class bool cannot be subclassed further. Its only instances are False and True 布尔类型的转化

Python内置的字符串处理函数整理字符串长度获取

Python内置的字符串处理函数整理字符串长度获取:len(str)例:print'%slengt By xuanfeng6666 at 2014-06-01 139 阅读 0 回复 0.0 希赛币 Python内置的字符串处理函数整理 ?字符串长度获取:len(str) 例:print '%s length=%d' % (str,len(str)) ?字母处理 全部大写:str.upper() 全部小写:str.lower() 大小写互换:str.swapcase() 首字母大写,其余小写:str.capitalize() 首字母大写:str.title() print '%s lower=%s' % (str,str.lower()) print '%s upper=%s' % (str,str.upper()) print '%s swapcase=%s' % (str,str.swapcase()) print '%s capitalize=%s' % (str,str.capitalize()) print '%s title=%s' % (str,str.title()) ?格式化相关 获取固定长度,右对齐,左边不够用空格补齐:str.rjust(width) 获取固定长度,左对齐,右边不够用空格补齐:str.ljust(width) 获取固定长度,中间对齐,两边不够用空格补齐:str.center(width) 获取固定长度,右对齐,左边不足用0补齐.zfill(width) print '%s ljust=%s' % (str,str.ljust(20))

Python如何针对任意多的分隔符拆分字符串操作

Python如何针对任意多的分隔符拆分字符串操作 本篇文章小编和大家分享一下Python cookbook(字符串与文本)针对任意多的分隔符拆分字符串操作,文中会结合实例形式进行分析Python使用split()及正则表达式进行字符串拆分操作相关实现技巧,对Python开发感兴趣或者是想要学习Python开发技术的小伙伴可以参考下哦。 问题:将分隔符(以及分隔符之间的空格)不一致的字符串拆分为不同的字段。 解决方案:使用更为灵活的re.split()方法,该方法可以为分隔符指定多个模式。 说明:字符串对象的split()只能处理简单的情况,而且不支持多个分隔符,对分隔符周围可能存在的空格也无能为力。 # example.py # # Example of splitting a string on multiple delimiters using a regex import re #导入正则表达式模块 line = 'asdf fjdk; afed, fjek,asdf, foo' # (a) Splitting on space, comma, and semicolon parts = re.split(r'[;,\s]\s*', line) print(parts) # (b) 正则表达式模式中使用“捕获组”,需注意捕获组是否包含在括号中,使用捕获组导致匹配的文本也包含在最终结果中 fields = re.split(r'(;|,|\s)\s*', line) print(fields) # (c) 根据上文的分隔字符改进字符串的输出 values = fields[::2] delimiters = fields[1::2] delimiters.append('') print('value =', values) print('delimiters =', delimiters) newline = ''.join(v+d for v,d in zip(values, delimiters)) print('newline =', newline) # (d) 使用非捕获组(?:...)的形式实现用括号对正则表达式模式分组,且不输出分隔符 parts = re.split(r'(?:,|;|\s)\s*', line)

python_内置函数_练习3

本练习的重点:通过实现与内置函数相同功能的函数来达到锻炼提升编码能力的目的。 1.abs(x)函数 返回一个数的绝对值。 参数可以是一个整数或浮点数。 如果参数是一个复数,则返 回它的模。 如果 x 定义了 abs(),则 abs(x) 将返回 x.abs()。 2.class complex([real[, imag]]) 函数 返回值为 real + imag*1j 的复数,或将字符串或数字转换为复数。如果第一个形参 是字符串,则它被解释为一个复数,并且函数调用时必须没有第二个形参。 当从字符串转换时,字符串在 + 或 - 的周围必须不能有空格。例如 complex('1+2j') 是合法的,但 complex('1 + 2j') 会触发 ValueError 异常。 3.isinstance(object, classinfo) 函数 如果参数 object 是参数 classinfo 的实例或者是其 (直接、间接或 虚拟) 子类则返回 True。 否则返回 False。 如果 classinfo 是类型对象元组(或由其他此类元组递归 组成的元组),那么如果 object 是其中任何一个类型的实例就返回 True。 如果

classinfo 既不是类型,也不是类型元组或类型元组的元组,则将引发 TypeError 异 常。 In [25]:print(abs(-1)) print(abs(-1.212)) print(abs(complex('1+2j'))) # 返回 sqrt(1+4) a = complex('1+2j') 1 1.212 2.23606797749979 请实现下面的函数,模仿abs函数的功能,返回数字的绝对值。 In [23]:import math # 方法1 def my_abs_1(number): if type(number) == int or type(number) == float: if number < 0: return number*(-1) else: return number elif type(number) == complex: return math.sqrt(number.real**2 + number.imag**2) #方法2 # 判断变量类型,可以使用isinstance函数, # 该函数的第一个参数是需要检查类型的对象, # 第二个参数可以是数据类型,也可以是一个元组, # 元组里是多个数据类型,只要满足其中一个就返回True def my_abs_2(number): if isinstance(number, (float,int)): if number < 0: return number*(-1) else: return number elif isinstance(number, complex): return math.sqrt(number.real**2 + number.imag**2) if __name__ == "__main__": print(abs(-1), end = " ") print(abs(-1.212), end = " ") print(abs(complex('1+2j')), end = " \n") print(my_abs_1(-1), end = " ") print(my_abs_1(-1.212), end = " ") print(my_abs_1(complex('1+2j')), end = " \n") print(my_abs_2(-1), end = " ") print(my_abs_2(-1.212), end = " ") print(my_abs_2(complex('1+2j')), end = " ") 1 1.21 2 2.23606797749979 1 1.21 2 2.23606797749979

【IT专家】python 字符串操作

本文由我司收集整编,推荐下载,如有疑问,请与我司联系 python 字符串操作 2017/08/24 0 name=“My \t name is {name} and age is {age}”print(name.capitalize()) #将name的值首字母大写print(name.count(“a”)) #输出a这个字符的出现的个数print(name.center(50,”-”)) #一共打印50个,其他用-代替print(name.endswith(“ex”)) #结尾是否包含exprint(name.expandtabs(tabsize=30)) #将字符串中的\t 转化为30个空格print(name[name.find(“name”):]) #find查找的意思字符串也可以进行切片,返回的结果为name及后面的一行内容 print(name.format(name=“wang”,age=23))print(name.format_map({“name”:”wang”,”age ”:23})) #字典的格式。。和format的结果一样print(“ab123”.isalnum()) #判断是否包含字母和数字,如果包含则返回为trueprint(“ab124”.isalpha()) #判断是否包含纯英文字符,如果是则返回为true,大小写不区分print(“122”.isdigit()) #判断是否为整数,如果为整数则返回为trueprint(“al1”.isidentifier()) #判断是不是一个合法的标识符(就是判断是不是合法的变量名)print(“aLL”.islower()) #判断是不是小写,是则返回trueprint(“aLL”.isnumeric()) #判断是不是数字,是则返回trueprint(“aLL”.isspace()) #判断是不是空格print(“My Name Is “.istitle()) #判断每个字符串的首字母大写,是的话就为trueprint(“my name is “.isupper())#判断是否是大写print(‘+’.join([‘1’,’2’,’3’])) #将列表的值转变为字符串的形式这个输出结果为:1+2+3print(name.ljust(50,”*”))print(name.rjust(50,”*”))print(“WANG”.lower())#将大写变成小写print(“wang”.upper()) #将小写边城大写print(“\nwang”.lstrip()) #取消左边的空格和回车print(“wang1\n”.rstrip())#去掉右边的空格和回车print(“ \nabng\n”.strip())#将左边和右边的空格和回车都去掉print(“wang han”.replace(‘a’,’A’,1))#将字符串中的a替换为大写的A,只替换其中一个print(‘wang wang’.rfind(‘a’)) #找到最右边的那个字符的下标print(‘1+2+3+4’.split(‘+’)) #以+号为分隔符,输出为列表的格式print(‘wang LI’.swapcase()) #将大写小反转print(‘wang han’.title()) #将每个字符串的首字母大写 ?tips:感谢大家的阅读,本文由我司收集整编。仅供参阅!

相关文档
相关文档 最新文档