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 
  • 32
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值