python全天课视频(8)

1、将"gloryroad"按照如下规则进行加密:

字母对应的Asscii码值进行加密,并且在码值前面加上码值长度
如g对应的码值为ord(“g”)=103,则字母g加密结果为3103
3是Asscii的长度
"gloryroad"正确输出加密结果为:
“31033108311131143121311431112973100”

def encode_str(s):
    encoded_str=""
    for i in s:
        encoded_str+=str(len(str(ord(i))))+str(ord(i))
    return encoded_str
2、将上题中的加密字符串进行解密

方法有2种:
方法1:利用while循环,观察加密后的规律,想办法遍历所有的内容

def  decode_str(s):
    index=0
    decoded_str=""
    while index < len(s):
        decoded_str+=chr(int(s[(index+1):(index+int(s[index]+1))]))
        index=index+int(s[index])+1
return decoded_str

方法2:递归实现

#encoding=utf-8
decrypt_result=""
def get_data(data):
    global decrypt_result
    if len(data)==0:
        print("解密结果为:"+decrypt_result)
    else:
        num=int(data[0])
        decrypt_result+=chr(int(data[1:(num+1)]))
        get_data(data[(num+1):])

在这里插入图片描述

result=[]
def func(s):
    global result
    i=0
    if len(s) >i:
        result.append(chr(int(s[1:int(s[i])+1])))
        func(s[int(s[i])+1:])
        return result
s=“31033108311131143121311431112973100”
print(func(s))

在这里插入图片描述

3、字符串

(1)原始字符串
所有的字符串都是直接按照字面的意思来使用,没有转义特殊或者不能打印的字符,原始字符串除
在字符串的第一个引号前面加上字母“r”(不区分大小写)以外,与普通字符串有着几乎完全相同的语法。

>>> s1="adf\nsd"
>>> print(s1)
adf
sd
>>> print(type(s1))
<class 'str'>
>>> print(r"gloryroad's test training course \n 'yes'")
gloryroad's test training course \n 'yes'

在这里插入图片描述

>>> print("1\n2")
1
2
>>> print(r"1\n2")#加r之后不需要转义了
1\n2
>>> print(R"1\2")#加r之后不需要转义了
1\2
>>> print(R"1\\2")#加r之后不需要转义了
1\\2
>>> print("1\2")
1
>>> print("1\\2")
1\2

在这里插入图片描述
(2)字节字符串
只需要在定西字符串时候转换成字节字符串。

>>> s3="aer23".encode("utf-8")
>>> print(s3)
b'aer23'
>>> print(type(s3))
<class 'bytes'>

在这里插入图片描述

>>> "abc"
'abc'
>>> type("abc")
<class 'str'>
>>> type(b"abc")
<class 'bytes'>
>>> type(b"中国")
  File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
>>> "中国".encode("gbk")
b'\xd6\xd0\xb9\xfa'
>>> s=b'\xd6\xd0\xb9\xfa'
>>> print(s)
b'\xd6\xd0\xb9\xfa'
>>> print(s.decode("gbk"))
中国

在这里插入图片描述
打印单双引号:

>>> import os
>>> os.linesep
'\r\n'
>>> print('\'')
'
>>> print('"')
"
>>> print('\"')
"
>>>

在这里插入图片描述
字符换运算

>>> a="a"
>>> id(a)
2512741199296
>>> a="a"+"b"
>>> id(a)
2512743931160
>>> a
'ab'
>>> id(a)
2512743931160
>>> a
'ab'
>>> id("ab")
2512743931160
>>> "ab"*4
'abababab'
>>> "a"+"b"+"c"
'abc'
>>> "".join(["1","2"])
'12'
>>> "abc{}".format("x")
'abcx'
>>> "abc{1}{0}".format("x","y")
'abcyx'
>>> "%s=%s"%(1,2)
'1=2'
>>> "%d=%d"%(1,2)
'1=2'
>>> "%.2=%.2f"%(1,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: unsupported format character '=' (0x3d) at index 3
>>> "%.2f=%.2f"%(1,2)
'1.00=2.00'
>>> "%.2f=%.2f"%(1.999,2.555)
'2.00=2.56'

在这里插入图片描述

>>> a="abc"
>>> a[0]
'a'
>>> for i in range(len(a)):
...     print(a[i])
...
a
b
c
>>> for i in a:
...     print(i)
...
a
b
c
>>> a[:]
'abc'
>>> a[::-1]
'cba'
>>> a[::2]
'ac'
>>> a[1:]
'bc'
>>> a[5:]
''
>>> "a" in "abc"
True
>>> "a" not in "abc"
False
>>> "a" == "a"
True
>>> "a"!="a"
False
>>> "a" is "a"
True
>>> "a" is not "a"
False

在这里插入图片描述
小练习:
s=“I am a boy!”,统计一下首字母为“a”的单词。

s="I am a boy!"
result=0
for  word in s.split():
    if word[0]=="a":
        result+=1
print(result)

在这里插入图片描述

" ".join(list(map(lambda x:x[::-1],s.split()[::-1])))

在这里插入图片描述

>>> "%e" %100000000000000
'1.000000e+14'
>>> "%e" %100000000000001
'1.000000e+14'
>>> "%x"%100000000000
'174876e800'
>>> "%o"%100000000000
'1351035564000'
>>> name="ruby"
>>> print("my name is %s and \ weight is %d kg" %(name,21))
my name is ruby and \ weight is 21 kg
>>>
>>> from string import Templete
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'Templete'
>>> from string import Template
>>> s=Template('There are ${key1} ${key2} Quotations symbols')
>>> print(s.substitute(key2="python",key1=3))
There are 3 python Quotations symbols

在这里插入图片描述

4、strip()函数
>>> "   abc   ".strip()
'abc'
>>> "*****abc********".strip("*")
'abc'
>>> "###***abc***###".strip("*#")
'abc'
>>> map(lambda x:ord(x),range(97,123))
<map object at 0x000002DB83F69BA8>
>>> list(map(lambda x:chr(x),range(97,123)))
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>> "".join( list(map(lambda x:chr(x),range(97,123))))
'abcdefghijklmnopqrstuvwxyz'
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

在这里插入图片描述

>>> "##**adddsj***###".strip('#*')
'adddsj'
>>> "##**adddsj***###".lstrip('#*')
'adddsj***###'
>>> "##**adddsj***###".rstrip('#*')
'##**adddsj'

在这里插入图片描述

5、常用字符串操作–大小写互换
>>> "abc".lower()
'abc'
>>> "ABC".lower()
'abc'
>>> "ABC".upper()
'ABC'
>>> "A".lower() =="a"
True
>>> "1".lower()
'1'
>>> "abc bcd".capitalize()#字符串的第一个字母大写
'Abc bcd'
>>> "abc DEF".swapcase()#大小写互换
'ABC def'
>>> string.capwords("abc def")#每个单词的首字母大写
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'string' is not defined
>>> import string
>>> string.capwords("abc def")#每个单词的首字母大写
'Abc Def'
>>> "abc bcd".title()#每个单词的首字母大写
'Abc Bcd'

在这里插入图片描述

6、常用的字符串操作-字符串对齐s.ljust()函数
>>> "abc".ljust(10)
'abc       '
>>> "abc".ljust(10,"$")
'abc$$$$$$$'
>>> "abc".rjust(10,"$")
'$$$$$$$abc'
>>> "abc".center(10,"$")
'$$$abc$$$$'
>>>
>>> str(1)
'1'
>>> str
<class 'str'>
>>> dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']
>>> type(string)
<class 'module'>
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

在这里插入图片描述

>>> "I am a boy,your a girl!yes!".split()
['I', 'am', 'a', 'boy,your', 'a', 'girl!yes!']
>>> list(map(lambda x:x.strip(string.punctuation),"I am a boy,your a girl!yes!".split()))
['I', 'am', 'a', 'boy,your', 'a', 'girl!yes']

在这里插入图片描述

7、Zfill()函数
>>> "1111".zfill(10)
'0000001111'
>>> "1111".zfill(3)
'1111'

在这里插入图片描述

8、常用的字符串操作–字符串的搜索s.find()函数

可在指定字符串范围内查找子字符串出现的位置

>>> "abc".find("a")
0
>>> "abc".find("x")
-1
>>> "abc".find("2")
-1
>>> "abc".index("c")
2
>>> "abc".index("x")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

在这里插入图片描述

>>> "allllllz".find("a")
0
>>> "allllllz".find("a",1)
-1
>>> "allllllz".find("z",5,10)#指定范围查找
7
>>> "ab ab ab".find("ab")
0
>>> import re
>>> re.findall(r"ab","ab ab ab")#正则查找
['ab', 'ab', 'ab']

在这里插入图片描述
查找一个字母:

>>> result=[]
>>> s="abbaaba"
>>> for i in range(len(s)):
...      if s[i]=="a":
...         result.append(i)
...
>>> print(result)
[0, 3, 4, 6]

在这里插入图片描述
查找多个字母:
方法1:

>>> result=[]
>>> s="abbaaba"
>>> for i in range(len(s)):
...     if s[i:i+2]=="ab":
...         result.append(i)
...
>>> print(result)
[0, 4]

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值