Python之字符串深入

Python之字符串深入

字符串常用方法

1.下标与元素

  • find
  • rfind
  • index
  • rindex
  • count
s = "apache.common.hadoop.hive.sql"
s.find("hive") # 从左往右计算索引Index,返回目标str的索引
21
s.find('hive',8) #从指定位置开始查找
21
s.rfind('p') #从右往左找目标元素的索引
19
s.index('p') #返回首次出现目标元素的位置
1
s.rindex('p')
19
s.count('p') #计算子字符在字符串中出现的次数
2

2.字符串切割和分区

  • split
  • rsplit
  • partition 将目标字符串按照指定字符切割为三个partition
  • rpartition
li = s.split(".")
print(li)
['apache', 'common', 'hadoop', 'hive', 'sql']
s.partition(".")
('apache', '.', 'common.hadoop.hive.sql')
s.rpartition(".")
('apache.common.hadoop.hive', '.', 'sql')
s = "2014-10-31"
s_list = s.split("-")
print(f"年:{s_list[0]}月:{s_list[1]}日:{s_list[2]}")
年:2014月:10日:31

3. 字符串连接join

li =  ["apple","peach","banana","pear"]
sep = ","
s=sep.join(li)
s
'apple,peach,banana,pear'
import timeit
timeit.timeit('"-".join(str(n) for n in range(100))',number=10000)
0.22487155600015285

4. lower(),upper(),capitalize(),title(),swapcase()

s  = "What is Your Name?"
s2 = s.lower()
s2
'what is your name?'
s.upper()
'WHAT IS YOUR NAME?'
s2.capitalize()
'What is your name?'
s.title()
'What Is Your Name?'
s.swapcase() # 驼峰命名
'wHAT IS yOUR nAME?'

5. replace

s = "中国,中国"
s2 = s.replace("中国","china")
s2
'china,china'

6. 字符映射表生成

  • maketrans() 生成字符串映射表
  • translate() 按映射表关系转换字符串并替换其中的字符
#将字符“abcdef123”一 一对应地转换成"uvwxyz@#$"
table = ' '.maketrans("abcdef123","uvwxyz@#$")
s = "Python is a greate programing language.i like it!"
s.translate(table)
'Python is u gryuty progruming lunguugy.i liky it!'

7. 删除两端,右端或左端地空白字符或连续的指定字符

  • strip()
  • rstrip()
  • lstrip()
s = "  abc  "
s2 = s.strip() #删除空白字符
s2
'abc'
'\n\nhello world \n\n \t'.strip()
'hello world'
"aaaasddf".strip("a") #删除指定字符
'sddf'
"aaaasddf".strip("ddf") #删除指定字符
'aaaas'
"aaaasddfaaa".rstrip("a") #删除字符串右端指定字符
'aaaasddf'
"aaaasddfaaa".lstrip("a") #删除字符串左端指定字符
'sddfaaa'

8. eval()

  • 内置函数eval()尝试将任意字符串转换为python表达式并求值
eval("3+4")
7
a = 3
b = 5
eval("a*b")
15

9. in

"a" in "abcdefg"
True

10. startswith,endswith()

s = 'To be or not to be.'
s.startswith("T")
True
s.startswith("To be")
True
s.endswith("to be.")
True

11. 判断类型:

* isalnum()
* isalpha()
* isdigit()
* isupper()
* islower()
"1234abcd".isalnum() # 是否为数字或字母
True
"1234abcd".isalpha() # 是否为字母
False
"1234abcd".isdigit() #是否为数字
False
"abcd".isupper() # 是否为大写字母
False
"abcd".islower() # 是否为小写字目
True

12. 字符串显示

* center(width,char=" ") 居中
* ljust() 左对齐
* rjust() 右对齐
'hello world'.center(20)
'    hello world     '
'hello world'.ljust(20,"=")
'hello world========='
'hello world'.rjust(20,"*")
'*********hello world'

字符串典型应用

字符串常量

  • 8位长度随机密码生成算法(验证码)
import string
import random
x = string.digits+string.ascii_letters+string.punctuation #数字+字母++分隔符
code =" ".join([random.choice(x) for i in range(8)]) #随机挑选x中的某个字符,挑选8次生成列表,列表中的字符再被空格join为字符串
print(code)
) p 7 : x O w Q
  • 发红包算法
import random

def red_packet(total,num):
    # total 红包总额
    # num红包数量
    each = []
    #已发红包金额
    already = 0
    for i in range(1,num): #range(a,b)-->[a,b)
        t = random.randint(1,(total-already)-(num -i)) #至少为剩下的每个人留一块钱
        each.append(t) #将每个人拿的红包额度记录到each列表
        already += t
    #剩余所有钱发给最后1个人
    each.append(total-already)
    random.shuffle(each)
    return each


for i in range(5):
    each = red_packet(50,6)
    print(each)
[4, 25, 1, 18, 1, 1]
[1, 40, 1, 1, 4, 3]
[2, 4, 7, 29, 1, 7]
[15, 2, 6, 11, 4, 12]
[19, 1, 2, 8, 19, 1]

可变字符串

import io
s = "Hello,world"
sio = io.StringIO(s)
sio.getvalue()
'Hello,world'
sio.seek(7)
7
sio.write("there!")
6
sio.getvalue()
'Hello,wthere!'
  • 字符串加密解密
def crypt(source, key):
    from itertools import cycle
    result = ''
    temp=cycle(key) #将密码字key变成可迭代对象
    for ch in source:
        result = result +chr(ord(ch)^ord(next(temp))) #密码的ASCII码与加密码字进行异或操作得到结果
    return result

source = "No romatic in China"
key = "i love you so"
print("before encrypted:",source)

encrypted = crypt(source, key)
print("after encrypted:",encrypted)

decrypted = crypt(encrypted,key)
print("after decrypted:",decrypted)
before encrypted: No romatic in China
�Ic
after decrypted: No romatic in China
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值