1.字符串基本操作

import oss1='i love python how are you'
#print(s1[8])#y
#print(s1[88])#error#利用分片截取字符串的子字符串
#print(s1[7:13])#python
#print(s1[7:])#python how are you
#print(s1[7::2])#pto o r os2='a b c d e f g'
#print(s2[0::2])#abcdefgs3='abc'
print(s3*10)#abcabcabcabcabcabcabcabcabcabc
'''
print('python' in s1)#True
print('python' in s2)#False
print('python' not in s1)#False
print('python' not in s2)#True
'''#print( len(s3))#3
#print( max(s3))#c
#print( min(s3))#a

2.字符串格式化基础

#字符串格式化基础
#字符串格式化:静态+动态
#hello bill,hello lak,hello world,对这三个子字符串来说,前面的hello是静态的,后面的 bill、lak、world是动态的。
#字符串的格式化,就是将一个或多个值替换另一个字符串的标记
#静态+动态的这种标记称为模板
#%可以格式化字符串,%出现在两个地方:一个是标记里面。一个是运算求余
#模板里面有静态部分,也有动态部分#定义一个模板
s0="hi %s my name is %s"
values=('world','lak');#元组 tuple
print(s0 % values)#hi world my name is lak#%f %d
from  math import pi
s0="hi %d my name is %.2f"
values=(456,pi);#元组 tuple
print(s0 % values)#hi 456 my name is 3.14s0="hi %d my name is %f"
values=(456,pi);#元组 tuple
print(s0 % values)#hi 456 my name is 3.141593
#输出%--用%%
s0="hi %%d my name is %f"
values=(pi);#元组 tuple
print(s0 % values)#hi %d my name is 3.141593s0="hi %%%d my name is %f"
values=(456,pi);#元组 tuple
print(s0 % values)#hi %456 my name is 3.141593
#值与标记要一致,个数也要一样

3.使用tmplate类格式化字符串--class string.Template(template)

#3.使用tmplate类格式化字符串--class string.Template(template)
#tmplate可以得知你的这个变量的意义
#tmplate它不在标准的API里面,属于字符串模板的使用模块中。
#通过类的构造器参数来传入字符串模板,然后通过标记,标记通过 $标记,为字符串模板来替换这个值,通过关键字:参数,或者字典来提供
from string import Templates = Template('$who likes $what,yes,$what')
s0=s.substitute(who='tim', what='kung pao')
print(s0)#tim likes kung pao,yes,kung pao#s = Template('$sstitute likes $what,yes,$what')#这里会KeyError: 'sstitute'
s = Template('${sst}itute likes $what,yes,$what')#这里会KeyError: 'sstitute'
s0=s.substitute(sst='tim', what='kung pao')#
print(s0)#timitute likes kung pao,yes,kung paos = Template('${sstitute} likes $what,yes,$what')#这里会KeyError: 'sstitute'
s0=s.substitute(sstitute='tim', what='kung pao')#
print(s0)#tim likes kung pao,yes,kung pao#说明,最好在要替换的单词中,加上 { },方便 确认s = Template('${dollar} $$ 相当于多少  ${pounds}')
s0=s.substitute(dollar=20, pounds='k英镑')
print(s0)#20 $ 相当于多少  k英镑#dict0={20:'ok_20',30:'ok_30',40:'ok_40',50:'ok_50'}
print('**************')
#dict0={}
#dict0['dollar']='ok_20'
#dict0['pounds']='ok_30'
dict0={'dollar':'ok_20','pounds':'ok_30'}
s = Template('${dollar} $$ 相当于多少  ${pounds}')
s0=s.substitute(dict0)
print(s0)#ok_20 $ 相当于多少  ok_30

4.使用format方法格式化字符串

# -*- coding: UTF-8 -*-
print 'Hello World!'
#使用format方法格式化字符串
print('hello world')
#标记(格式化参数)
#如何进行格式化  "template".format(...)
#之前一种是%
#一种是teplate类#按顺序来指定格式化参数值
s1='Today is {},the temperature is {} degrees.'
print(s1.format(30,'30---ok'))
print(s1.format('30','xref我们30---ok'))#使用命名格式化参数
s2='today is {week},the temperature is {degree} degrees'
print(s2.format(week='weeik00',degree=98))
print(s2.format(degree='98我们',week='weeik00'))s3="today is {week},{},the {} templature is {degree} degrees";
print(s3.format("abcd",1234,456789,degree='98我们',week='weeik00'))
'''
Hello World!
hello world
Today is 30,the temperature is 30---ok degrees.
Today is 30,the temperature is xref我们30---ok degrees.
today is weeik00,the temperature is 98 degrees
today is weeik00,the temperature is 98我们 degrees
today is weeik00,abcd,the 1234 templature is 98我们 degrees
'''
#取得指定顺序的值
#按顺序来指定格式化参数值 序号从0开始
s4='Today is {week},{1},the temperature is {0} degrees.,{degree}'
print(s4.format("abcd","123400",'30---ok--00','30---ok---11',week='week-value',degree="degree-xxx"))#获取列表中的指定值
fullname=["bill","gates"]
s5="Mr. {name[1]}"
print(s5.format(name=fullname))#Mr. gatess4='Today is {week},{1},the temperature is {0} degrees.,{degree}'
print(s4.format("abcd","123400",'30---ok--00','30---ok---11',week='week-value',degree="degree-xxx"))#Today is week-value,123400,the temperature is abcd degrees.,degree-xxximport math
s6="the {mod.__name__} module defines the value {mod.pi} for PI"
print(s6.format(mod=math))#the math module defines the value 3.14159265359 for PI

5.控制字符串格式化参数

# 更进一步控制字符串格式化参数# 字符串格式化类型符
# repr函数  repr('a') = 'a'  str('a') = a
from string import Template
s1 = "原样输出:{first!s}  调用repr函数:{first!r}  输出Unicode编码:{first!a}"
print(s1.format(first = "中"))
print(s1.format(first = "什么呀"))
print("repr() shows quotes: {!r}; str() doesn't: {!s} {!a}".format('test1', '你的家乡', '你的性别'))
# 将一个整数按浮点数格式输出s2 = "整数:{num}  浮点数:{num:f}"
print(s2.format(num=123))
s2 = "整数:{0}  浮点数:{1:f}"
print(s2.format(12,123))
s2 = "00整数:{0}  浮点数:{1:f}"
print(s2.format(12,123.257478))# 进制转换
s3 = "十进制:{num}  二进制:{num:b} 八进制:{num:o}  十六进制:{num:x}"
print(s3.format(num = 78))
s4="int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}"
print(s4.format(42))
s5="{0:d};  {1:x};  {2:o};  {3:b}"
print(s5.format(42,45,678,76))# 将整数按科学计数法
s4 = "科学计数法0:{num:e}"
print(s4.format(num =6789))
s4 = "科学计数法1:{num:E}"
print(s4.format(num =6789))
s4 = "科学计数法2:{0:e}"
print(s4.format(6789))
s4 = "科学计数法3:{0:E}"
print(s4.format(6789))
s4 = "科学计数法4:{0:!a}"
#print(s4.format('1'))#  将浮点数按百分比输出
s5 = "百分比0:{num:%}"
print(s5.format(num = 0.34))
s5 = "百分比1:{0:%}"
print(s5.format(0.34568))
s5 = "百分比2:{:.2%}"
print(s5.format(0.34568))'''
a  将字符串按Unicode编码输出
b  将一个整数格式化为一个二进制数
c  将一个整数解释成ASCII
d  将整数格式化为十进制的数
e/E  科学计数法表示
f/F  将一个整数格式化为浮点数,(nan和inf)转换为小写
g/G  会根据整数值的位数,在浮点数和科学计数法之间切换,在整数位超过6位时,与e相同,否则与f相同
o   将一个整数格式化为八进制
s   按原样格式化字符串
x/X 将一个整数格式化为十六进制数
%   将一个数值格式化为百分比形式'''

6.字段宽度、精度和千位分隔符

# 字段宽度、精度和千位分隔符
#  100,000,000,000# 让一个数值在宽度为12的范围内输出,如果数值没到12位,左侧填充空格
print("a:{num:12}".format(num = 32))
print("a:{num:12}".format(num = 456767632))print('{:<30}'.format('left aligned'))
print('{:>30}'.format('right aligned'))
print('{:^30}'.format('centered'))
print('{:*^30}'.format('centered') ) # use '*' as a fill charprint('{:+f}; {:+f}'.format(3.14, -3.14) ) # show it always
print('{: f}; {: f}'.format(3.14, -3.14) ) # show a space for positive numbers
print('{:-f}; {:-f}'.format(3.14, -3.14) ) # show only the minus -- same as '{:f}; {:f}'print('{:,}'.format(1234567890))
print('Correct answers: {:.2%}'.format(19/22))
print('Correct answers: {:.3%}'.format(19/22))
print('Correct answers: {:.4%}'.format(19/22))#  create table
print("{header1:10}{header2:6}".format(header1="姓名",header2="年龄"))
print("{cell11:10}{cell12:6}".format(cell11 = "Bill", cell12=43))
print("{cell21:10}{cell22:6}".format(cell21 = "Mikerxe", cell22 = 34))from math import pi
print("float number:{pi:.3f}".format(pi = pi))
print("float number:{pi:20.4f}".format(pi = pi))# 截取字符串
print("{msg:.5}".format(msg = "Hell1World"))
print("{:.5}".format( "Hell1World"))# 千位分隔符
print("One googol is {:,}".format(10 ** 100))
print("One googol is {}".format(10 ** 100))

7.符号、对齐、用0填充

# 符号、对齐和用0填充
# 12  00000012from math import pi
print("{pi:012.3f}".format(pi = pi))
print("{pi:#12.3f}".format(pi = pi))# <(左对齐) ^(中对齐) >(右对齐)
print("{pi:#<12.3f}".format(pi = pi))
print("{pi:#^12.3f}".format(pi = pi))
print("{pi:#>12.3f}".format(pi = pi))print("{pi:0=12.3f}".format(pi = -pi))print('-----------------------')
print('{:<12.9f}'.format(23.5678941))
print('{:>25.5f}'.format(23.5678941))
print('{:^25.6}'.format(23.5678941))
print('{:*^25.6}'.format(23.5678941))
print('{:0^25.6}'.format(23.5678941))
00000003.1423.142
3.142#######
###3.142####
#######3.142
-0000003.142
-----------------------
23.56789410023.5678923.5679
*********23.5679*********
00000000023.5679000000000

8.center方法

#bytearray.center(width[, fillbyte])
# 字符串方法:center# ^
print("<" + "hello".center(30) + ">")
# <      hello       >
print("<{:^30}>".format("hello"))
print("<{:}{:}>".format("hello","456"))
#
print("<" + "hello".center(20, "*") + ">")
print("<{:*^20}>".format("hello"))
<            hello             >
<            hello             >
<hello456>
<*******hello********>
<*******hello********>

9.find方法

# 字符串方法:find
#str.find(sub[, start[, end]])
s = "hello world"
print(s.find("world"))print(s.find("abc"))print(s.find("o"))
print(s.find("o",6))print(s.find("l",5,9))
print(s.find("l",5,10))

10 join方法

# 字符串方法:join# 用于连接序列中的元素,split方法list = ["a", "b", "c", "d", "e"]
s = '*'
print(s.join(list))
print("xy".join(list))# C:\abc\xyz
# /abc/xyz
# c:\usr\local\nginx\
# /usr/local/nginx/dirs = '','usr','local','nginx',''
linuxPath = '/'.join(dirs)
print(linuxPath)windowPath = 'C:' + '\\'.join(dirs)
print(windowPath)numList = [1,2,3,4,5,6]
#print('1'.join(numList))#error
#print('1'.join(numList.__iter__()))#error
print(" ".join('%s' %id for id in numList))

11.字符串方法:split方法

# 字符串方法:split方法
s1 = "a b c d e f"
print(s1.split())s2= "a*b*c*d*e"
print(s2.split("*"))path = "/usr/local/nginx"
pathList = path.split('/')
print(pathList)
windowPath = "D:" + "\\".join(pathList)
print(windowPath)

12.字符串方法:split方法

# 字符串方法:split方法
#str.split(sep=None, maxsplit=-1)
s1 = "a b c d e f"
print(s1.split())s2= "a*b*c*d*e"
print(s2.split("*"))path = "/usr/local/nginx"
pathList = path.split('/')
print(pathList)#['', 'usr', 'local', 'nginx']
windowPath = "D:" + "\\".join(pathList)#D:\usr\local\nginx
print(windowPath)
print('1,2,3'.split(','))
print('1,2,3'.split(',', maxsplit=1))
print('1,2,,3,'.split(','))
'''
['a', 'b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e']
['', 'usr', 'local', 'nginx']
D:\usr\local\nginx
['1', '2', '3']
['1', '2,3']
['1', '2', '', '3', '']
'''

13.字符串方法:lower、upper和capwords函数

# 字符串方法:lower、upper和capwords函数
#bytearray.lower()
#bytearray.upper()
#string.capwords(s, sep=None)
print("HEllo".lower())
print("hello".upper())list = ["Python", "Ruby", "Java","KOTLIN"]
if "Kotlin" in list:print("找到Kotlin了")
else:print("未找到Kotlin")for lang in list:if "kotlin" == lang.lower():print("找到Kotlin了")break;from string import capwords
s = "i not only like Python, but also like Kotlin"
print(capwords(s))s = "i,not,only,like,Python,  but,also,like,Kotlin"
print(capwords(s,','))
'''
hello
HELLO
未找到Kotlin
找到Kotlin了
I Not Only Like Python, But Also Like Kotlin
I,Not,Only,Like,Python,  but,Also,Like,Kotlin
'''

14.字符串方法:replace和strip

# 字符串方法:replace和strip
#bytearray.replace(old, new[, count])
#bytearray.strip([chars])
s = "abcdaedf"
print(s.replace("a", "12345"))
print("xzyabcexwfexyz34xyz56778".replace("xyz","aa"))
print(s.replace("xyz","aa"))print("   geekori.com   ".strip())
print(" <  geekori.com  >  ".strip())langList = ["python", "java", "ruby", "scala", "perl"]
lang = "   python   "
if lang in langList:print("找到了python")
else:print("未找到python")if lang.strip() in langList:print("找到了python")
else:print("未找到python")s = "***  $$*  Hello * World   ***$$$  "
print(s.strip(" *$"))print(b'   spacious   '.strip())
print(b'www.example.com'.strip(b'cmowz.'))
print(b'wwwexamplecom'.strip(b'cmowz'))
print(b'xrwwwexamplew3com'.strip(b'cmowz'))
print('  xrwwwexamplew3com  '.strip('cmowz'))
print("  xrwwwexamplew3com  ".strip("cmowz"))
print("***  $$*  Hello * World   ***$$$  ".strip(" *$"))
print("***  $$*  Hello * World   ***$$$  ".strip("*$"))
'''
12345bcd12345edf
xzyabcexwfeaa34aa56778
abcdaedf
geekori.com
<  geekori.com  >
未找到python
找到了python
Hello * World
b'spacious'
b'example'
b'example'
b'xrwwwexamplew3'xrwwwexamplew3com  xrwwwexamplew3com
Hello * World$$*  Hello * World   ***$$$
'''

15.字符串方法:translate和maketrans

# 字符串方法:translate 和 maketrans#bytearray.translate(table, delete=b'')
#static bytearray.maketrans(from, to)# translate:替换单个字符#s = "I not only like python, but also like kotlin."
s = "awk, kawn "
table = s.maketrans("ak", "*$")
print(table)
print(s.translate(table))
table1 = s.maketrans("ak", "*$", " ")#第三个参数是要删除的字符串
print(table1)
print(s.translate(table1))print(b'read this short text'.translate(None, b'aeiou'))
#print('read this short text'.translate(None, 'aeiou'))
table = s.maketrans("aeiou","!@#$%")
print("read this short text".translate(table))table = s.maketrans('aeiou','!@#$%')
print('read this short text'.translate(table))#table = s.maketrans('aeiou','!@#')
#print('read this short text'.translate(table))
'''
{97: 42, 107: 36}
*w$, $*wn
{97: 42, 107: 36, 32: None}
*w$,$*wn
b'rd ths shrt txt'
r@!d th#s sh$rt t@xt
r@!d th#s sh$rt t@xt
'''

python中基础知识(五)相关推荐

  1. python语言中、用来表示赋值的符号是_第二章Python语言基础知识

    第二章Python语言基础知识 2.1 Python语言基础知识 2.1.1标识符与关键字 在Python语言中,对程序中各个元素命名加以区分,这种用来标识变量.函数.类等元素的符号称为标识符. Py ...

  2. post获取重定向的链接 python_【转载】python面试基础知识(四) 网络部分

    最近,小编在整理python面试基础知识,看了很多博客.文章和咨询了一些大厂公司大牛.了解到,在python面试的时候,不仅要求你有项目经验,还要考试代码呢!今天,小编和大家分享一下python面试基 ...

  3. Python考试基础知识

    Python考试基础知识 一.python的基本语法(包括包的导入) 二.序列类型的数据结构(重点考察列表及其基本方法) 1.前言 2.list 内容简介 2.1 list简介 2.2 list常用函 ...

  4. python必备基础代码-新手上路必学的Python函数基础知识,全在这里了(多段代码举例)...

    原标题:新手上路必学的Python函数基础知识,全在这里了(多段代码举例) 导读:函数是Python中最重要.最基础的代码组织和代码复用方式.根据经验,如果你需要多次重复相同或类似的代码,就非常值得写 ...

  5. python基础知识-一篇文章搞定Python全部基础知识

    原标题:一篇文章搞定Python全部基础知识 前言: 1.Python软件安装 第一章.字符串及数字变量 1.变量 要点提炼:Python变量为强类型动态类型.换言之,变量很任性,你给他int,他就是 ...

  6. python爬虫——基础知识

    python爬虫--基础知识 一.网页基础知识 二.爬虫的思路 1.HTML文档(超文本) 三.ROBOTS协议 四.浏览器发送HTTP请求的过程 1.http请求过程 2.请求 五.SSL连接错误 ...

  7. python 概率分布函数_如何在Python中实现这五类强大的概率分布

    匿名用户 1级 2016-04-25 回答 首页 所有文章 观点与动态 基础知识 系列教程 实践项目 工具与框架应用 工具资源 伯乐在线 > Python - 伯乐在线 > 所有文章 &g ...

  8. python前端基础知识总结 及部分练习题

    python前端基础知识总结 知识总结 认识Python 发展历史 版本选择 python2.7是python2的最后一个版本,到2020年将不再维护 python3.6是python3最新的版本,是 ...

  9. python详细基础知识笔记

    详细基础知识笔记 注: ·第一章 学习准备 1.1高级语言.机器语言.汇编语言 1.2 汇编.解释 1.3 静态语言.脚本语言 1.4 Python的历史 1.5 Python语言的优点.缺点 1.6 ...

最新文章

  1. 杭电 hdu 2096
  2. 基础-计算机及操作系统和应用程序的概念
  3. 什么叫单模光纤_什么叫单模光纤_单模光纤的特点是什么
  4. Daily Scrum 10.26
  5. 基于jquery的php分页,基于jQuery封装的分页组件
  6. 200820C阶段一通用链表
  7. JAVA 网络编程小记
  8. jQuery文档操作之删除操作
  9. 工具分享 | LiqunKit 综合漏洞利用工具(下载地址在文末)
  10. 趣头条的区块链实验:为何金币贬值了6.6倍?
  11. php表格行数怎么设置,表格怎么排版
  12. Android多开/分身检测
  13. terraria泰拉瑞亚
  14. 重庆南川金佛山中医院“扶正消瘤贴”专家评估研讨会圆满落幕
  15. 黑马程序员_JAVA之IO流的(转换流,数据输入输出流等)
  16. 称为超级计算机,哪台机器被称为世界上最快的超级计算机?
  17. 105 THREE.JS 手动实现相机沿焦点旋转
  18. 变年轻特效是什么软件?快把这些软件收好
  19. python通过ssh连接linux,执行命令
  20. windows安全警报怎么关闭_10月23日,鄂州华容进行防空警报鸣放,请不要惊慌!...

热门文章

  1. AI 图片截取、ffmpeg使用及安装, anaconda环境,图片标注(labelme),模型训练(yolov5),CUDA+Pytorch安装及版本相关问题
  2. Pikachu系列——RCE
  3. java 1900年_JDK与1900年01月01日
  4. 蓝桥杯练习题:计算保留100位小数的圆周率
  5. 【新手向】C语言中“=”与“==”的区别及使用方法
  6. Python-Level1-day02:数据基本运算(基础知识;变量及其内存图;数据类型,运算符)
  7. 计算机专业可以进厂么,计算机研究生毕业进入工厂工作,月薪只有四千,原因实在太真实了...
  8. 简谈FPGA设计中不同设计方法资源消耗对比
  9. 学python对数学要求吗_python 学习和数学知识 - 文章分类 - 风中小郎君 - 博客园...
  10. 搞一下整车以太网技术 | A1 整车以太网技术概述