Python 自学笔记 总结 1.0 变量及函数

本文详细介绍了Python中的字符串格式化、集合的定义、操作和运算,包括成员运算、交并差运算、比较运算以及集合的方法。此外,还探讨了函数的基础知识,包括函数的定义、参数使用、返回值以及函数的嵌套调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

九.格式化

格式化字符串(通过center,ljust,rjust方法做居中,左对齐和右对齐的处理,在字符串左侧补零,使用zfill方法。)

s='hello,world'
#center方法以宽度20将字符串居中并在两侧填充*
print(s.center(20,'*') )

    运行后:
        #****hello,world****
       (123456789...........)

#rjust方法以宽度20将字符串右对齐并在左侧填充空格.
print(s.rjust(20) )

    运行后:
      #         hello,world
       123456789...... .....

#ljust方法以宽度20将字符串左对齐并在右侧填充~
print(s.ljust(20,'~') )

    运行后:
        #hello,world~~~~~~~~

#在字符串左侧补0
print('33',zfill(5))

    运行后:
        #00033

print('-33',zfill(5))

    运行后:
        #-0033

print函数输出字符串

a=321
b=123
print('%d*%d=%d'%(a,b,a*b)
运行后:
#321*123=39483

字符串的方法

a=321
b=123
print('{0}*{1}={2}'.format(a,b,a*b)

 

运行后:
#321*123=39483


如需进一步控制格式化变量值形式,参考以下:

变量值 占位符 格式化结果 说明
3.1415926 {:.2f} '3.14' 保留小数点后两位
3.1415926 {:+.2f} '+3.14' 带符号保留小数点后两位
-1 {:+.2f} '-1.00' 带符号保留小数点后两位
3.1415926 {:.0f} '3' 不带小数
123 {:0>10d} '0000000123' 左边补0,补够十位
123 {:x<10d} '123xxxxxxx' 右边补x,补够十位
123 {:  >10d} '       123' 左边补空格,补够十位
123 {:  <10} '123       '

右边补空格,补够十位

123456789 {:,  } '123,456,789' 逗号分隔格式
0.123 {:.2%} '12.30%' 百分比格式
123456789 {:.2e} '1.23e+08' 科学计数法格式

 

修剪操作(将原字符串修剪掉左右两端空格之后的字符串)

S='    tuling_python@126.com    /t/r/n'
#strip方法获得字符串修剪左右两侧空格之后的字符串
print(s.strip() )

    运行后:
#tuling_python@126.com

 替换操作:replace

S='hello,world'
print(s.replace('o','@'))

    运行后:
#hell@,w@rld

print(s.replace('o','@',1))

    运行后:
#hell@,world

拆分/合并操作   split(默认空格进行拆分)

S='I love you'
words=s.split()
print(words)

    运行后:
#['I','love','you']

print('#'.join(words))

    运行后:
#I#love#you

 


不默认空格,指定其他字符拆分

S='I#love#you#so#much'
words=s.split('#')
print(words)

    运行后:
#['I','love','you','so','much']


words=s.split('#',3)
print(words)

    运行后:
#['I','love','you','so#much']

 




十.集合

常用数据结构之集合(set)

集合定义:把一定

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值