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 ...
随机推荐
- Swift与OC混合开发
一.Swift调用OC 1. 创建{targetName}-Bridging-Header.h头文件,在BuildSetting -> bridging 2. Swift文件调用的OC中的类的头 ...
- mybatis自动生成代码工具(逆向工程)
MyBatis自动生成实体类(逆向工程) MyBatis属于一种半自动的ORM框架,它需要我们自己编写sql语句和映射文件,但是编写映射文件和sql语句很容易出错,所以mybatis官方提供了Gene ...
- C# ASCII码和英文字母相互转换和ASCII码对照表
1.字母转换成ASCII码 string str = "hello"; ]; array = System.Text.Encoding.ASCII.GetBytes(str); / ...
- struts2注解方式的验证
struts2的验证分为分编程式验证.声明式验证.注解式验证.因现在的人越来越懒,都追求零配置,所以本文介绍下注解式验证. 一.hello world 参考javaeye的这篇文章,按着做一次,起码有 ...
- struts2类型转换1
概述 从一个 HTML 表单到一个 Action 对象, 类型转换是从字符串到非字符串. HTTP 没有 “类型” 的概念. 每一项表单输入只可能是一个字符串或一个字符串数组. 在服务器端, 必须把 ...
- IOS 表单含有input框和有position: fixed导致错位的问题
在input框聚焦失焦的时候,都调用以下js即可 setScrollTop() { let scrollTop = document.body.scrollTop + document.documen ...
- QT开发资料
QT开发入门资料 https://tmr.js.org/p/cc37608/ QT学习之路: https://www.devbean.net/
- Linux 错误: $'\r': command not found
是linux无法解析$'\r'.这其实是windows与linux系统的差异导致的. 因为linux上的换行符为\n,而windows上的换行符为\r\n.所以脚本到linux上就无法解析了. 通常的 ...
- python异常整理
一.操作excel 时异常 1.PermissionError: [Errno 13] Permission denied (1)原因:权限错误:[Errno 13] 权限被拒绝 错误产生的原因是文件 ...
- leetcode-第11场双周赛-5088-等差数列中缺失的数字
题目描述: 自己的提交: class Solution: def missingNumber(self, arr: List[int]) -> int: if len(arr) == 2: re ...