python基础篇三:函数

本文详细介绍了Python的基础知识,包括字符函数、格式化字符串、列表、字典、元组和集合的操作,如字符串连接、分割、列表切片、字典增删元素、元组不可变性及集合的添加、删除元素等。还涵盖了None值的使用和各种运算符的解释。
摘要由CSDN通过智能技术生成

1.字符函数

(1)字符串常用操作

string1 = "hello python,I'm a beginner"
print(string1)
string2 = string1.replace("hello", "hi")  #将某个子串替换成另外的子串
print(string2)  
string3 = string1.capitalize()  # 句子的首字母大写
print(string3)
string4 = string1.title() #每个单词首字母大写
print(string4)
string5 = string1.upper()  #全部字母大写
print(string5)
string6=string1.lower() #全部字母小写
print(string6)
print('#123'.startswith('#')) #判断字符串是否以某个字符开头

print('123#'.endswith('*')) #判断字符串是否以某个字符结尾

print("   123  ".strip()) #去掉前后两边的空格或者指定字符

print("***123***".strip('*')) #去掉前后两边的空格或者指定字符

print("   123   ".lstrip()) #去掉左边的空格或者指定字符

print("   123    ".rstrip()) #去掉右边的空格或者指定字符

print('123456789'.isnumeric())  #判断字符串是不是全部数字

print('abcd'.isalpha()) #判断字符串是不是全部字母 

(2) 连接字符串

用-连接字符,生成一个新的字符串0-1-2-3-4-5-6-7-8-9

print('-'.join('0123456789')) 
print('-'.join(['1', '2', '3', '4', '5']))  

(3) 分割字符串

将字符串在-处分割,组成一个列表 [‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’]

print('0-1-2-3-4-5'.split('-'))

(4) 字符串通用操作

in 判断子串是否在字符串之内

print('he' in 'hello')  
print('llo' not in 'hello')

连接字符串 helloworld

print('hello' + 'world')

复制字符串 hello hello hello

 print('hello ' * 3) 

切片操作

string1="hello python,I'm a beginner"
string2="helop"

print(string1[0])  #通过索引来获取某个元素,索引从0开始 输出h

print(string1[4])  #索引从0开始 输出o

print(string1[0:5])  #切片操作,从0开始不包括5 输出hello

print(string1[0:12])  #切片操作,从0开始不包括12,12个是逗号 输出hello python

print(string2[0:5:2])  #切片操作,从0开始不包括5,2代表步长(隔两个取) 输出hlp

print(len(string2)) #获取字符串长度 27
print(max(string2)) #获取最大字符 o
print(min(string2)) #获取最小字符 e
print(string2.index('l')) #某个元素第一次出现的下标 

2.格式化字符串

三种方法格式化字符串:

(1)占位符

%s 表示字符串
%d 表示整数
%f 表示浮点数

print(" %s 你好, 你%d月的话费是%f元 " % ('Tom',
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值