赞
踩
提示:本节主要介绍python序列结构,包括字符串、列表、元组、字典、集合
str1 = "What's your name" # 字符串中出现单引号,可以用双引号
str2 = 'What\'s your name'
str3 = "\"Yes\",he says." # 当单引号中出现单引号,或者双引号中出现双引号,可以使用反斜杠\对字符原样输出。
str4 = """how
are
you
""" # 使用三引号可以换行输出
s.capitalize() # 首字母大写
s.upper() # 全部大写
s.lower() # 全部小写
s.swapcase() # 大小写互换
s.title() # 每个用特殊字符或数字隔开的单词首字母大写
# 语法:str.center(width, fillchar = None)
s1 = s.center(20,'%') # 用%填充
s2 = s.center(20) # 用空白填充
# str.find()通过元素找索引,找到返回索引,找不到返回-1
# str.index()通过元素找索引,找到返回索引,找不到返回error
s = 'Andrew'
s_1 = s.find('w')
s_1 = s.index('e')
s = " alexW # % 123 "
s_1 = s.strip()
s_2 = s.strip(%)
# 注意:str.strip()的方式只能暂时删除,要想永久删除字符串的空白,需将删除的操作关联到变量。
str.count(s)
str.split()
str.split(':')
s = '小小小'
s1 = s.replace('小','大',1) # 只替换第一个出现的,默认替换所有
str.isdigit() # 是否由数字组成
str.isalpha() # 是否由字母组成
str.isalnum() # 是否由字母或数字组成
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','*'))
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
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
def addSeperator(s):
return f"{
int(s):,}" # f-string中,:是格式说明符
列表由一系列按特定顺序排列的元素组成,元素可以是任何数据类型。因此,可以给列表指定一个表示复数的名称。
创建的列表大多都是动态的,意味着列表创建后,可随着程序运行增删元素。
motor = ['honda','yamaha','suzuki']
motor[0] = 'ducati'
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。