Python基础学习(四):序列结构(字符串、列表、元组、字典、集合)

文章目录


前言

提示:本节主要介绍python序列结构,包括字符串、列表、元组、字典、集合

一、字符串

(一)基础知识

1. 字符串定义

str1 = "What's your name" # 字符串中出现单引号,可以用双引号
str2 = 'What\'s your name'
str3 = "\"Yes\",he says." # 当单引号中出现单引号,或者双引号中出现双引号,可以使用反斜杠\对字符原样输出。
str4 = """how
are 
you
""" # 使用三引号可以换行输出

2.字符串大小写转换

s.capitalize() # 首字母大写
s.upper() # 全部大写
s.lower() # 全部小写
s.swapcase() # 大小写互换
s.title() # 每个用特殊字符或数字隔开的单词首字母大写

3.居中(用空白/其他字符填充)

# 语法:str.center(width, fillchar = None)
s1 = s.center(20,'%') # 用%填充
s2 = s.center(20) # 用空白填充

4.查找

# str.find()通过元素找索引,找到返回索引,找不到返回-1
# str.index()通过元素找索引,找到返回索引,找不到返回error
s = 'Andrew'
s_1 = s.find('w')
s_1 = s.index('e')

5. 删除字符串前后的空格

s = "  alexW # % 123   "
s_1 = s.strip()
s_2 = s.strip(%)
# 注意:str.strip()的方式只能暂时删除,要想永久删除字符串的空白,需将删除的操作关联到变量。

6. 计算字符串中某字符/某字符串的个数

str.count(s)

7. 分割(相当于str→list)

str.split()
str.split(':')

8.字符串替换 replace函数

s = '小小小'
s1 = s.replace('小','大',1) # 只替换第一个出现的,默认替换所有

9.is系列

str.isdigit() # 是否由数字组成
str.isalpha() # 是否由字母组成
str.isalnum() # 是否由字母或数字组成

(二)例题

1. 替换

Write a Python function that takes in a string and returns a modified string replacing each letter ‘T’ and ‘t’ with a ‘*’.

def allBut(s):
	print(s.replace('T','*').replace('t','*'))

2. Caesar encryption

Write a Python function caesarEncryption(s, n) to convert all characters in string s into lowercase and create a Caesar encryption with shift n, leaving the non-letter characters unchanged, then return the result.

def caesarEncyption(s,n):
    t = s.lower()
    s1 = ""
    for i in t:
        if i == " ":
            s1 = s1 + i
        else:
            if ord(i)+n > 0x7A:
                s1 = s1 + chr(ord(i)+n-26)
            elif ord(i)+n < 0x61:
                s1 = s1 + chr(ord(i)+n+26)
            else:
                s1 = s1 + chr(ord(i)+n)
    return s1

3. 字符串中的find函数

Write a Python function findReplace(s) to find the first appearance of the substring ‘not’ and ‘poor’ from a given string, if ‘not’ is followed by ‘poor’, replace the whole ‘not’…‘poor’ substring with ‘good’. Return the resulting string. Otherwise return the original string.

def findReplace(s):
    n = s.find('not')
    p = s.find('poor', n)
    if 0 <= p < len(s):
        return s.replace(s[n:p+4], 'good')
    else:
        return s

4. 给整数加千分位符

def addSeperator(s):
	return f"{
     int(s):,}" # f-string中,:是格式说明符

二、列表

(一)基础知识

1. 列表简介

  列表由一系列按特定顺序排列的元素组成,元素可以是任何数据类型。因此,可以给列表指定一个表示复数的名称。

2. 修改列表元素

创建的列表大多都是动态的,意味着列表创建后,可随着程序运行增删元素。
motor = ['honda','yamaha','suzuki']
motor[0] = 'ducati'

3.添加元素

  • 32
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值