Small turtle Python thirteenth lecture after the topic--014 string

 String methods and comments
capitalize()
  
  Change the first character of a string to uppercase
  
  casefold()
  
  Change all characters of the entire string to lowercase
  
  center(width)
  
  Center the string and pad it with spaces to a new string of length width
  
  count(sub[,start[,end]])
  
  Returns the number of times sub appears in the string, the start and end parameters indicate the range, optional.
  
  encode(encoding='utf-8', errors='strict')
  
  Encodes the string in the encoding format specified by encoding.
  
  endswith(sub[,start[,end]])
  
  Checks if the string ends with sub substring, returns True if so, False otherwise. The start and end parameters represent the range and are optional.
  
  expandtabs([tabsize=8])
  
  Convert the tab symbol (\t) in the string to spaces. If no parameter is specified, the default number of spaces is tabsize=8.
  
  find(sub[,start[,end]])
  
  Check whether sub is contained in the string, if so, return the index value, otherwise return -1, start and end parameters indicate the range, optional.
  
  index(sub[,start[,end]])
  
  Same as find, but raises an exception if sub is not in string.
  
  isalnum()
  
  Returns True if the string has at least one character and all characters are letters or numbers, otherwise returns False.
  
  isalpha()
  
  Returns True if the string has at least one character and all characters are letters, otherwise returns False.
  
  isdecimal()
  
  Returns True if the string contains only decimal digits, False otherwise.
  
  isdigit()
  
  Returns True if the string contains only numbers, otherwise returns False.
  
  islower()
  
  Returns True if the string contains at least one case-sensitive character and those characters are all lowercase, otherwise returns False.
  
  isnumeric()
  
  Returns True if the string contains only numeric characters, otherwise returns False.
  
  isspace()
  
  Returns True if the string contains only spaces, otherwise returns False.
  
  istitle()
  
  Returns True if the string is titled (all words start with uppercase, the rest of the letters are lowercase), False otherwise.
  
  isupper()
  
  Returns True if the string contains at least one case-sensitive character and those characters are all uppercase, otherwise returns False.
  
  join(sub)
  
  Insert a string between all characters in sub, using the string as the delimiter.
  >>> str5 = 'Fishc' >>> str5.join('12345') '1Fishc2Fishc3Fishc4Fishc5'
  light (width)
  
  Returns a left-aligned string padded with spaces to a new string of length width.
  
  lower()
  
  Converts all uppercase characters in a string to lowercase.
  
  lstrip()
  
  Remove all spaces from the left of the string
  
  partition(sub)
  
  Find the substring sub, divide the string into a 3-tuple (pre_sub, sub, fol_sub), if the string does not contain sub, return ('original string', '', '')
  
  replace(old,new[,count])
  
  Replace the old substring in the string with the new substring. If count is specified, the replacement will not exceed count times. >>> str7 = 'i love fishdm and seven' 
  >>> str7.replace('e','E',2) 'i lovE fishdm and sEven'
  rfind(sub[,start[,end]])
  
  类似于find()方法,不过是从右边开始查找。
  
  rindex(sub[,start[,end]])
  
  类似于index()方法,不过是从右边开始。
  
  rjust(width)
  
  返回一个右对齐的字符串,并使用空格填充至长度为width的新字符串。
  
  rpartition(sub)
  
  类似于partition()方法,不过是从右边开始查找。
  
  rstrip()
  
  删除字符串末尾的空格。
  
  split(sep=None,  maxsplit=-1)
  
  不带参数默认是以空格为分隔符切片字符串,如果maxsplit参数有设置,则仅分隔maxsplit个子字符串,返回切片后的子字符串拼接的列表。
  >>> str7.split ()   ['i', 'love', 'fishdm', 'and', 'seven']
  splitlines(([keepends]))
  
  按照‘\n’分隔,返回一个包含各行作为元素的列表,如果keepends参数指定,则返回前keepends行。
  
  startswith(prefix[,start[,end]])
  
  检查字符串是否以prefix开头,是则返回True,否则返回False。start和end参数可以指定范围检查,可选。
  
  strip([chars])
  
  删除字符串前边和后边所有的空格,chars参数可以定制删除的字符,可选。
  
  swapcase()
  
  翻转字符串中的大小写。
  
  title()
  
  返回标题化(所有的单词都是以大写开始,其余字母均小写)的字符串。
  
  translate(table)
  
  根据table的规则(可以由str.maketrans(‘a’,‘b’)定制)转换字符串中的字符。>>> str8 = 'aaasss sssaaa'
  >>> str8.translate(str.maketrans('s','b'))     'aaabbb bbbaaa'
  upper()
  
  转换字符串中的所有小写字符为大写。
  
  zfill(width)
  
  返回长度为width的字符串,原字符串右对齐,前边用0填充。
  
 
 
测试题:
0.还记得如何定义一个跨越多行的字符串吗(请至少写出两种实现的方法)?
方法一:

str1 = '''待我长发及腰,将军归来可好?
此身君子意逍遥,怎料山河萧萧。
天光乍破遇,暮雪白头老。
寒剑默听奔雷,长枪独守空壕。
醉卧沙场君莫笑,一夜吹彻画角。
江南晚来客,红绳结发梢。'''

 

方法二:

str2 = '待卿长发及腰,我必凯旋回朝。\
昔日纵马任逍遥,俱是少年英豪。\
东都霞色好,西湖烟波渺。\
执枪血战八方,誓守山河多娇。\
应有得胜归来日,与卿共度良宵。\
盼携手终老,愿与子同袍。'

 

方法三:

str3 = ('待卿长发及腰,我必凯旋回朝。'
'昔日纵马任逍遥,俱是少年英豪。'
'东都霞色好,西湖烟波渺。'
'执枪血战八方,誓守山河多娇。'
'应有得胜归来日,与卿共度良宵。'
'盼携手终老,愿与子同袍。')

 

1.  三引号字符串通常我们用于做什么使用?

三引号字符串不赋值的情况下,通常当作跨行注释使用,例如:

 

2.  file1 = open(' C: \windows\temp\readme. txt' ,  ' r' ) 表示以只读方式打开“C: \windows\temp\readme. txt”这个文本文件,但事实上是错,知道为什么吗?你会如何修改?

会报错是因为在字符串中,我们约定“\t”和“\r”分别表示“横向制表符(TAB)”和“回车符”,因此并不会按照我们计划的路径去打开文件。

Python 为我们铺好了解决的道路,只需要使用原始字符串操作符(R或r)即可:

file1=open(r'C:\windows\temp\readme.txt','r')

 

3.  有字符串:str1 = ' <a href="http: //www. fishc. com/dvd" target="_blank">鱼C资源打包</a>',请问如何提取出子字符串

str1[16:38]

 

4. 如果使用负数作为索引值进行分片操作,按照第三题的要求你能够正确目测出结果吗?  

str1[-45:-32]

 

5. 还是第三题那个字符串,请问下边语句会显示什么内容?str1[20:-36]

'fishc'

 

6. 据说只有智商高于150的鱼油才能解开这个字符串(还原为有意义的字符串):str1 ='i2sl54ovvvb4e3bferi32s56h;$c43.sfc67o0cm99' 

str1[::3]

 

动动手

0. 请写一个密码安全性检查的脚本代码:check.py  
 程序演示:
 
自己写的错误代码: 混成一片进行判断
while True:
temp = input('输入密码')
# a = int(temp)
b=len(temp)
c ='''提升密码等级的方式:
1.密码必须由数字、字母及特殊字符三种组合
2.密码只能由字母开头
3.密码长度不能低于16位'''
d = '~!@#$%^&*()_=-/,.?<>;:[]{}\|'
while temp.isspace():
temp = input('重新输入密码')
print(temp,b)
if b<=8 or temp.isalnum():
print('低级密码')
print(c)
elif b > 16 and temp.isalnum() and (d in temp):
print('高')
print('请继续保持')
elif b>8 or b<16 or temp.isalnum() or (d in temp ):
print('中')
print(c)

方法一:

str1 = "~!@#$%^&*()_=-/,.?<>;:[]{}\|"
has_str1 = 0
has_num = 0
has_alpha = 0
t = 'y'
while t == 'y':
password = input("请输入需要检查的密码组合:")
length = len(password)
while(password.isspace() or length == 0):
password = input('您输入的密码为空(或空格),请重新输入:')
for i in password:
if i in str1:
has_str1 = 1
if i.isdigit():
has_num = 1
if i.isalpha():
has_alpha = 1
has = has_str1 + has_num + has_alpha
if length <= 8 or password.isalnum():
level = "低"
if length > 8 and has ==2:
level = "中"
if length >= 16 and has == 3 and password[0].isalpha():
level = "高"
print("您的密码安全等级评定为:%s"%level)
if level == "高":
print("请继续保持")
else:
print("""请按以下方式提升您的密码安全级别:
1.密码必须由数字、字母及特殊字符三种组合
2.密码只能由字母开头
3.密码长度不能低于16位""")
t = input("还要再测试么?(”y“继续,其他退出)")
注意:特殊的数字开头的高级密码没有判断

方法二:
symbols = "~!@#$%^&*()_=-/,.?<>;:[]{}\|"
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
nums = '0123456789'
t = 'y'
while t == 'y':
passwd = input('请输入密码:')
length = len(passwd)
#判断长度
while(passwd.isspace() or length == 0):
passwd = input('您输入的密码为空(或空格),请重新输入:')
length = len(passwd)
if length <= 8:
flag_len = 1
elif 8 < length <16:
flag_len = 2
else:
flag_len = 3
flag_con = 0
#判断是否包含特殊字符
for each in passwd:
if each in symbols:
flag_con +=1
break
#判断是否包含字母
for each in passwd:
if each in chars:
flag_con += 1
break
#判断是否包含数字
for each in passwd:
if each in nums:
flag_con += 1
break
#打印结果
while 1:
print("您的密码安全级别评定为:",end='')
if flag_len == 1 or flag_con == 1:
print("低")
elif flag_len == 2 or flag_con == 2:
print("中")
else:
print("高")
print("请继续保持")
break
print("""请按以下方式提升您的密码安全级别:
1.密码必须由数字、字母及特殊字符三种组合
2.密码只能由字母开头
3.密码长度不能低于16位""")
break
t = input("还要再测试么?(”y“继续,其他退出)")
注意:判断高级密码没有条件 其他类型都是高级

方法三:
str0 = """请按以下方式提升您的密码安全级别: 
1.必须由数字、字母及特殊字符三种组合(仅限:~!@#$%^&*()_=-/,.?<>;:[]{}\|)
2.密码只能由字母开头
3.密码长度不能低于16位"""

str1 = '您的密码安全级别评定为:低\n' + str0 + """
4.替王尼玛给隔壁老王送上一把水果刀
5.告诉你的孩子,他是充话费下送的
6.召集另外三只小甲鱼,喂他们突变剂,救纽约人民于水火
"""
str2 = '您的密码安全级别评定为:中\n' + str0 + """
4.扶老奶奶过马路,帮室友补袜子
"""
str3 = '您的密码安全评定为:高\n请继续保持!'

special = "~!@#$%^&*()_=-/,.?<>;:[]{}\|"
letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
number = '0123456789'
t = 'y'

while t == 'y':
password = input("请输入需要检查的密码组合:")

# 用num来统计字符类型出现次数
num = 0
a = b = c = 0
# 输入的不能为空
while password == '':
password = input("不能为空,请重新输入:")
# 计算num的值,如果输入的全部是字符,那么num=0,所以才会有<=1
if password.isnumeric() or password.isalpha():
num = 1
else:
for i in password:
if a == 0 and i in special:
num += 1
a = 1
elif b == 0 and i in number:
num += 1
b = 1
elif c == 0 and i in letter:
num += 1
c = 1
if password[0] in letter and num == 3 and len(password) >= 16:
print(str3)
elif num >= 2 and len(password) >= 8:
print(str2)
elif num <= 1 and len(password) < 8:
print(str1)
t = input("还要再测试么?(”y“继续,其他退出)")

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326168975&siteId=291194637