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 ...
随机推荐
- MYSQL分数排名
编写一个 SQL 查询来实现分数排名.如果两个分数相同,则两个分数排名(Rank)相同.请注意,平分后的下一个名次应该是下一个连续的整数值.换句话说,名次之间不应该有“间隔”. +----+----- ...
- leetcode-两个数组交集(包含重复元素)
Python解法代码: class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: ...
- windows常用
host文件位置:C:\Windows\System32\drivers\etc
- flutter 插件
flutter_spinkit loading动画
- oracle11g 导出表报EXP-00011:table不存在。
oracle11g 导出表报EXP-00011:table不存在. oracle11g,在用exp命令备份数据库时,如果表中没有数据报EXP-00011错误,对应的表不存在.这导致对应的空表无法备份. ...
- git学习记录2(远程库管理)
学习参考地址:https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000 本编随笔只是自己对 ...
- 日常 java+雅思+训练题1
今天主要学了一些类似c中的一些语句,java也是一样类似的,只有一些点需要稍微注意一下,一些语句是新增的需要知道. 完完全全新学的知识就是class和instance的区别.如何创建实例.数据的封装. ...
- 自动化测试工具2-testcomplete
今天来说说testcomplete的使用 录了一个简单案例视频,网址如下:https://v.qq.com/x/page/f05116a062y.html 第一步是创建一个工程: 输入工程名,和选择工 ...
- CSS如何让文字垂直居中?
在说到这个问题的时候,也许有人会问CSS中不是有vertical-align属性来设置垂直居中的吗?即使是某些浏览器不支持我只需做少许的CSS Hack技术就可以啊!所以在这里我还要啰嗦两句,CSS中 ...
- markdown转为pdf文件
要求: 把.md格式转为.pdf格式,并批量处理,最后将多个pdf文件合并为一个pdf并以文件名作为书签名 解决思路: 1.md格式的markdown文件转为html 为了将 md 格式转换成 htm ...