day14 python02---字符串
day02
数字相关的转换
bin() 2进制
oct() 8进制
hex() 16进制
字符串
定义:它是一个有序的字符的集合,用于存储和表示基本的文本信息,‘’或“”或‘’‘ ’‘’中间包含的内容称之为字符串
特性:
1.只能存放一个值
2.不可变
3.按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序
补充:
1.字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符均取消特殊意义,在引号前面加r,如name=r'l\thf'
2.unicode字符串与r连用必需在r前面,如name=ur'l\thf'
class str(object):
def capitalize(self):
首字母变大写 def center(self, width, fillchar=None):
原来字符居中,不够用空格补全 def count(self, sub, start=None, end=None):
从一个范围内的统计某str出现次数 def encode(self, encoding='utf-8', errors='strict'):
以encoding指定编码格式编码,如果出错默认报一个ValueError,除非errors指定的是 def endswith(self, suffix, start=None, end=None):
Return True if S ends with the specified suffix, False otherwise. def expandtabs(self, tabsize=8):
将字符串中包含的\t转换成tabsize个空格 def find(self, sub, start=None, end=None):
Return the lowest index in S where substring sub is found def format(self, *args, **kwargs):
格式化输出
三种形式:
形式一.
>>> print('{0}{1}{0}'.format('a','b'))
aba 形式二:(必须一一对应)
>>> print('{}{}{}'.format('a','b'))
Traceback (most recent call last):
File "<input>", line 1, in <module>
IndexError: tuple index out of range
>>> print('{}{}'.format('a','b')) 形式三:
>>> print('{name} {age}'.format(age=12,name='lhf')) def index(self, sub, start=None, end=None):
查找第一个出现该字符串的下标 def isalpha(self):
至少一个字符,且都是字母才返回True def isdigit(self):
如果都是整数,返回True def isidentifier(self):
字符串为关键字返回True def islower(self):
至少一个字符,且都是小写字母才返回True def isnumeric(self):
Return True if there are only numeric characters in S, def isspace(self):
至少一个字符,且都是空格才返回True def istitle(self):
首字母大写则返回True def isupper(self): # real signature unknown; restored from __doc__
Return True if all cased characters in S are uppercase and there is def join(self, iterable): # real signature unknown; restored from __doc__
#对序列进行操作(分别使用' '与':'作为分隔符)
>>> seq1 = ['hello','good','boy','doiido']
>>> print ' '.join(seq1)
hello good boy doiido
>>> print ':'.join(seq1)
hello:good:boy:doiido #对字符串进行操作 >>> seq2 = "hello good boy doiido"
>>> print ':'.join(seq2)
h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o #对元组进行操作 >>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido #对字典进行操作 >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello #合并目录 >>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido' S.join(iterable) -> str Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
"""
return "" def lower(self):
"""
S.lower() -> str Return a copy of the string S converted to lowercase.
"""
return "" def partition(self, sep):
以sep为分割,将S分成head,sep,tail三部分 def replace(self, old, new, count=None):
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring def rfind(self, sub, start=None, end=None):
S.rfind(sub[, start[, end]]) -> int def rindex(self, sub, start=None, end=None):
S.rindex(sub[, start[, end]]) -> int def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
"""
S.rsplit(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the
delimiter string, starting at the end of the string and
working to the front. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified, any whitespace string
is a separator.
"""
return [] def rstrip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return "" def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
以sep为分割,将S切分成列表,与partition的区别在于切分结果不包含sep,
如果一个字符串中包含多个sep那么maxsplit为最多切分成几部分
>>> a='a,b c\nd\te'
>>> a.split()
['a,b', 'c', 'd', 'e'] def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
"""
Python splitlines() 按照行('\r', '\r\n', \n')分隔,
返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如 果为 True,则保留换行符。
>>> x
'adsfasdf\nsadf\nasdf\nadf'
>>> x.splitlines()
['adsfasdf', 'sadf', 'asdf', 'adf']
>>> x.splitlines(True)
['adsfasdf\n', 'sadf\n', 'asdf\n', 'adf'] S.splitlines([keepends]) -> list of strings Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
"""
return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. def strip(self, chars=None): # real signature unknown; restored from __doc__
S.strip([chars]) -> str Return a copy of the string S with leading and trailing def swapcase(self): # real signature unknown; restored from __doc__
"""
大小写反转
S.swapcase() -> str Return a copy of S with uppercase characters converted to lowercase
and vice versa.
"""
return "" def title(self): # real signature unknown; restored from __doc__
"""
S.title() -> str Return a titlecased version of S, i.e. words start with title case
characters, all remaining cased characters have lower case.
"""
return "" def translate(self, table): # real signature unknown; restored from __doc__
"""
table=str.maketrans('alex','big SB') a='hello abc'
print(a.translate(table)) S.translate(table) -> str Return a copy of the string S in which each character has been mapped
through the given translation table. The table must implement
lookup/indexing via __getitem__, for instance a dictionary or list,
mapping Unicode ordinals to Unicode ordinals, strings, or None. If
this operation raises LookupError, the character is left untouched.
Characters mapped to None are deleted.
"""
return "" def upper(self): # real signature unknown; restored from __doc__
"""
S.upper() -> str Return a copy of S converted to uppercase.
"""
return "" def zfill(self, width): # real signature unknown; restored from __doc__
"""
原来字符右对齐,不够用0补齐 S.zfill(width) -> str Pad a numeric string S with zeros on the left, to fill a field
of the specified width. The string S is never truncated.
"""
return ""
str的方法
homework
# 1:编写for循环,利用索引遍历出每一个字符
# msg='hello egon 666' msg='hello egon 666' for i in range(len(msg)):
print(msg[i])
作业一
# 2:编写while循环,利用索引遍历出每一个字符
# msg='hello egon 666'
msg='hello egon 666'
count = 0 while count < len(msg):
print(msg[count])
count += 1
作业二
# 3:
# msg='hello alex'中的alex替换成SB msg='hello alex' print(msg)
print("修改后:",msg.replace('alex', 'SB'))
作业三
# 4:
# msg='/etc/a.txt|365|get'
# 将该字符的文件名,文件大小,操作方法切割出来 msg='/etc/a.txt|365|get'
msg_list = msg.split('|')
print("""
打印说明
1.文件名:{}
2.大 小:{}
3.方 法:{}
""".format(msg_list[0], msg_list[1], msg_list[2]))
作业四
# 编写while循环,要求用户输入命令,如果命令为空,则继续输入 flag = True
while flag:
if len(input(">>>").strip()) != 0:
flag = False
continue
作业五
# 编写while循环,让用户输入用户名和密码,如果用户为空或者数字,则重新输入 flag = True while flag:
username = input('username:').strip()
password = input('password:').strip()
if len(username) != 0 and not username.isdigit():
flag = False
continue
作业六
# 编写while循环,让用户输入内容,判断输入的内容以alex开头的,则将该字符串加上_SB结尾 while True:
s = input(">>>")
if s == 'q':
break
elif s.startswith('alex'):
s+='_SB'
print(s)
作业七
# 8.
# 1.两层while循环,外层的while循环,让用户输入用户名、密码、工作了几个月、每月的工资(整数),用户名或密码为空,或者工作的月数不为整数,或者
# 月工资不为整数,则重新输入
# 2.认证成功,进入下一层while循环,打印命令提示,有查询总工资,查询用户身份(如果用户名为alex则打印super user,如果用户名为yuanhao或者wupeiqi
# 则打印normal user,其余情况均打印unkown user),退出功能
# 3.要求用户输入退出,则退出所有循环(使用tag的方式)
flag = True while flag:
username = input('用户名:').strip()
password = input('密码:').strip()
work_time = input('工作时间:').strip()
salary = input('工资:').strip()
if len(username) == 0 or len(password) == 0 or not work_time.isdigit() or not salary.isdigit():
continue
else:
while flag:
choose = input("1.查询工资\n2.查询身份\n3.退出\n>>>")
if choose == '':
input('%s的工资是%s元'%(username, salary))
elif choose == '':
if username == 'alex':
input('supper user')
elif username == 'yuanhao' or username == 'wupeiqi':
input('normal user')
else:
input('unkown user')
elif choose == '' or choose == 'q':
flag = False
else:
input("Error")
作业八
day14 python02---字符串的更多相关文章
- Python全栈day14(字符串格式化)
一,%字符串格式化 1,使用%s 后面一一对应输入对应的字符串,%s可以接受任何参数 print ("I am %s hobby is zhangsan"%'lishi') pri ...
- 11.1 正睿停课训练 Day14
目录 2018.11.1 正睿停课训练 Day14 A 字符串 B 取数游戏(贪心) C 魔方(模拟) 考试代码 B C 2018.11.1 正睿停课训练 Day14 时间:3.5h 期望得分:100 ...
- python02 运算符,基本数据类型,整型,字符串
1.python开发IDE pycharm,python编写工具,, #专业版 #不需要汉化 注册码问题解决 https://www.cnblogs.com/evlon/p/4934705.html整 ...
- day14 Python format字符串格式化
.format字符串拼接 # -*- coding:utf8 -*- #不一一对应会报错 tp1 = "i am {}, age {}, {}".format("char ...
- day14 Python百分号字符串拼接
拼接 # -*- coding:utf8 -*- #%s字符串,%d数字msg = '%s am %s my %s is %s'% (2,"charon","pluto& ...
- Python之路,Day14 - It's time for Django
Python之路,Day14 - It's time for Django 本节内容 Django流程介绍 Django url Django view Django models Django ...
- 【JAVA零基础入门系列】Day6 Java字符串
字符串,是我们最常用的类型,每个用双引号来表示的串都是一个字符串.Java中的字符串是一个预定义的类,跟C++ 一样叫String,而不是Char数组.至于什么叫做类,暂时不做过多介绍,在之后的篇章中 ...
- 【JAVA零基础入门系列】Day14 Java对象的克隆
今天要介绍一个概念,对象的克隆.本篇有一定难度,请先做好心理准备.看不懂的话可以多看两遍,还是不懂的话,可以在下方留言,我会看情况进行修改和补充. 克隆,自然就是将对象重新复制一份,那为什么要用克隆呢 ...
- python学习 day14 (3月19日)----
04 json # 1. 用于多种语言 交互 编程语言通用数据 # 内置的 不需要安装直接导入使用 import json # 导入 # # dumps loads dump load # dic = ...
- day14(xml 编写及解析)
编写 xml的组成: 1.文档的声明 <?xml version='1.0' encoding='UTF-8' standalone='yes'> xml 表示标签的名字 encoding ...
随机推荐
- touch - 修改文件的时间戳记.
总览 touch [-acm][-r ref_file(参照文件)|-t time(时间值)] file(文件名)... 被废弃的版本: touch [-acm][ugly_time] file(文件 ...
- 随笔记录 shell脚本相关内容 2019-8-26
字符串截取: 假设变量为var=http://www.hao.com/123.htm1. # 号截取,删除左边字符,保留右边字符.echo ${var#*//}其中 var 是变量名,# 号是运算符, ...
- C/C++各个周期的学习
C/C++ 程序的生命周期 编写时: 要点:业务,数据结构,控制解耦:健壮:易修改:清晰简单无歧义:易重用:低耦合高内聚:易链接:速度快(时间复杂度,空间复杂度,cache友好): 书籍:<c+ ...
- 使用Process子类创建进程
#_author:来童星#date:2019/12/17# 使用Process子类创建进程from multiprocessing import Processimport timeimport os ...
- CSS——浮动及应用&清除浮动
浮动(float) 1.普通流(normal flow) 这个单词很多人翻译为 文档流 , 字面翻译 普通流 或者标准流都可以. 前面我们说过,网页布局的核心,就是用CSS来摆放盒子位置.如何把盒子摆 ...
- Android中onTouch方法的执行过程以及和onClick执行发生冲突的解决办法
$*********************************************************************************************$ 博主推荐 ...
- 双目立体匹配经典算法之Semi-Global Matching(SGM)概述:代价聚合(Cost Aggregation)
由于代价计算步骤只考虑了局部的相关性,对噪声非常敏感,无法直接用来计算最优视差,所以SGM算法通过代价聚合步骤,使聚合后的代价值能够更准确的反应像素之间的相关性,如图1所示.聚合后的新的代价值保存 ...
- electron-vue构建桌面应用
一.项目搭建 electron-vue是vue-cli和electron结合的项目,比单独使用vue构建起的electron项目要方便很多. 1.初始化项目并运行 vue init simulated ...
- UIWindow & UIWindowLevel笔记
一.UIWindow是一种特殊的UIView,通常在一个程序中只会有一个UIWindow,但可以手动创建多个UIWindow,同时加到程序里面.UIWindow在程序中主要起到三个作用: 1.作为容器 ...
- 关于group by的用法
重新回顾并理解group by. 首先设计一张表,表名为test 然后执行以下SQL语句: select name from test group by name 获得执行结果: 可是为了能够更好的理 ...