Python字符串深入学习

# -*- coding: utf-8 -*-
# 开发团队   :pip uninstall python
# 开发人员   :breakmyself
# 开发时间   :2019/9/4  17:24 
# 文件名称   :str_tlp.PY
# 开发工具   :PyCharm
#github主页:https://github.com/breakmyself
#字符串大小写转换
"""
title():将每个单词的首字母改为大写
lower():将整个字符串改为小写
upper():将整个字符串改为大写
"""
a = 'our domain IS  crazyit.org'
#将每个单词首字母大写
print(a.title())
#将每个字面小写
print(a.lower())
#将每个字符转换成大写
print(a.upper())
#删除空白行
"""
strip():删除字符串前后的空白
lstrip():删除字符串前面(左边)的空白
rstrip():删除字符串后面(右边)的空白
"""
s = '    this  is   a puppy       '
#删除左边空白
print(s.lstrip())
#删除两边空白
print(s.strip())
#删除右边空白
print(s.rstrip())
print(s)
s1 = 'i think it is a scarecrow'
#删除左边的 i/t/o/w字符
print(s1.lstrip('itow'))
#删除右边的i/t/o/w
print(s1.rstrip('itow'))
#删除两边的i/t/o/w
print(s1.strip('itow'))
#查找、替换相关方法
"""
startswith():判断字符串是否以指定字符串开头
endswith():判断字符串是否以指定字符串结尾
find:查找指定字符串中出现的位置,如果没有找到返回 -1
index():查找指定字符串在字符串中出现的位置,如果没有找到指定子串,则引发valueError错误
replace():使用指定字符串替换字符串中的目标子串
translate():使用指定的翻译映射表对字符串执行替换
"""
s2 = 'crazyit.org  is a  good site'
#判断s是否以crazyit开头的
print(s2.startswith('crazyit'))
#判断s是否以site结尾
print(s2.endswith('site'))
#获取s在字符串中的位置
print(s2.index('s'))
#查找s中org出现的位置
print(s2.find('org'))
#从索引9处开始查找 'org'出现的位置,不能使用index,会报错
print(s.find('org',9))
#print(s.index('org',9))
#将字符串中的org 换成 com
print(s2.replace('org','com'))
#将字符串中一个it 更换成  do
print(s2.replace('org','do',1))
#将字符串中所有字符串中的 it换成dapao
print(s2.replace('it','dapao'))
#定义翻译映射表:97(a)---945(α),98(b)----945(β),116(t)----964(π)
table = {97: 945,98: 946,116: 946}
print(s2.translate(table))
#字符串分割
#split():将字符串按指定分隔符分割成多个短语
#join():将多个短语连接成字符串
a = 'crazyit.org is  a good site'
print(a.split())
#使用空白对字符串进行分割,最多分割前两个单词
print(a.split(None,2))
#使用. 进行分割
print(a.split('.'))
mylist = a.split()
print('/'.join(mylist))
print(','.join(mylist))

执行结果

E:\py\venv\Scripts\python.exe E:/py/crazypython/str_tlp.py
Our Domain Is  Crazyit.Org
our domain is  crazyit.org
OUR DOMAIN IS  CRAZYIT.ORG
this  is   a puppy       
this  is   a puppy
    this  is   a puppy
    this  is   a puppy       
 think it is a scarecrow
i think it is a scarecr
 think it is a scarecr
True
True
14
8
-1
crazyit.com  is a  good site
crazyit.do  is a  good site
crazydapao.org  is a  good sdapaoe
crαzyiβ.org  is α  good siβe
['crazyit.org', 'is', 'a', 'good', 'site']
['crazyit.org', 'is', 'a good site']
['crazyit', 'org is  a good site']
crazyit.org/is/a/good/site
crazyit.org,is,a,good,site

Process finished with exit code 0

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值