首页 > 代码库 > day14 python02---字符串

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‘
技术分享
  1 class str(object):
  2     def capitalize(self): 
  3         首字母变大写
  4 
  5     def center(self, width, fillchar=None):
  6         原来字符居中,不够用空格补全
  7 
  8     def count(self, sub, start=None, end=None):
  9         从一个范围内的统计某str出现次数
 10 
 11     def encode(self, encoding=utf-8, errors=strict): 
 12         以encoding指定编码格式编码,如果出错默认报一个ValueError,除非errors指定的是
 13 
 14     def endswith(self, suffix, start=None, end=None): 
 15         Return True if S ends with the specified suffix, False otherwise.
 16         
 17     def expandtabs(self, tabsize=8): 
 18         将字符串中包含的\t转换成tabsize个空格
 19 
 20     def find(self, sub, start=None, end=None): 
 21         Return the lowest index in S where substring sub is found
 22 
 23     def format(self, *args, **kwargs):
 24         格式化输出
 25         三种形式:
 26         形式一.
 27         >>> print({0}{1}{0}.format(a,b))
 28         aba
 29 
 30         形式二:(必须一一对应)
 31         >>> print({}{}{}.format(a,b))
 32         Traceback (most recent call last):
 33           File "<input>", line 1, in <module>
 34         IndexError: tuple index out of range
 35         >>> print({}{}.format(a,b))
 36 
 37         形式三:
 38         >>> print({name} {age}.format(age=12,name=lhf))
 39 
 40 
 41     def index(self, sub, start=None, end=None): 
 42         查找第一个出现该字符串的下标
 43 
 44     def isalpha(self): 
 45         至少一个字符,且都是字母才返回True
 46 
 47     def isdigit(self): 
 48         如果都是整数,返回True
 49 
 50     def isidentifier(self): 
 51         字符串为关键字返回True
 52 
 53     def islower(self): 
 54         至少一个字符,且都是小写字母才返回True
 55 
 56     def isnumeric(self): 
 57         Return True if there are only numeric characters in S,
 58 
 59     def isspace(self):
 60         至少一个字符,且都是空格才返回True
 61 
 62     def istitle(self): 
 63         首字母大写则返回True
 64         
 65     def isupper(self): # real signature unknown; restored from __doc__
 66         Return True if all cased characters in S are uppercase and there is
 67 
 68     def join(self, iterable): # real signature unknown; restored from __doc__
 69         #对序列进行操作(分别使用‘ ‘与‘:‘作为分隔符)
 70         >>> seq1 = [hello,good,boy,doiido]
 71         >>> print  .join(seq1)
 72         hello good boy doiido
 73         >>> print :.join(seq1)
 74         hello:good:boy:doiido
 75 
 76 
 77         #对字符串进行操作
 78 
 79         >>> seq2 = "hello good boy doiido"
 80         >>> print :.join(seq2)
 81         h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
 82 
 83 
 84         #对元组进行操作
 85 
 86         >>> seq3 = (hello,good,boy,doiido)
 87         >>> print :.join(seq3)
 88         hello:good:boy:doiido
 89 
 90 
 91         #对字典进行操作
 92 
 93         >>> seq4 = {hello:1,good:2,boy:3,doiido:4}
 94         >>> print :.join(seq4)
 95         boy:good:doiido:hello
 96 
 97 
 98         #合并目录
 99 
100         >>> import os
101         >>> os.path.join(/hello/,good/boy/,doiido)
102         /hello/good/boy/doiido
103 
104 
105         S.join(iterable) -> str
106 
107         Return a string which is the concatenation of the strings in the
108         iterable.  The separator between elements is S.
109         """
110         return ""
111 
112     def lower(self):
113         """
114         S.lower() -> str
115 
116         Return a copy of the string S converted to lowercase.
117         """
118         return ""
119 
120     def partition(self, sep):
121         以sep为分割,将S分成head,sep,tail三部分
122 
123 
124     def replace(self, old, new, count=None): 
125         S.replace(old, new[, count]) -> str
126         Return a copy of S with all occurrences of substring
127 
128 
129     def rfind(self, sub, start=None, end=None): 
130         S.rfind(sub[, start[, end]]) -> int
131 
132     def rindex(self, sub, start=None, end=None): 
133         S.rindex(sub[, start[, end]]) -> int
134 
135 
136     def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
137         """
138         S.rsplit(sep=None, maxsplit=-1) -> list of strings
139 
140         Return a list of the words in S, using sep as the
141         delimiter string, starting at the end of the string and
142         working to the front.  If maxsplit is given, at most maxsplit
143         splits are done. If sep is not specified, any whitespace string
144         is a separator.
145         """
146         return []
147 
148     def rstrip(self, chars=None): # real signature unknown; restored from __doc__
149         """
150         S.rstrip([chars]) -> str
151 
152         Return a copy of the string S with trailing whitespace removed.
153         If chars is given and not None, remove characters in chars instead.
154         """
155         return ""
156 
157     def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
158         以sep为分割,将S切分成列表,与partition的区别在于切分结果不包含sep,
159         如果一个字符串中包含多个sep那么maxsplit为最多切分成几部分
160         >>> a=‘a,b c\nd\te‘
161         >>> a.split()
162         [‘a,b‘, ‘c‘, ‘d‘, ‘e‘]
163 
164 
165     def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
166         """
167         Python splitlines() 按照行(\r, \r\n, \n)分隔,
168         返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如        果为 True,则保留换行符。
169         >>> x
170         adsfasdf\nsadf\nasdf\nadf
171         >>> x.splitlines()
172         [adsfasdf, sadf, asdf, adf]
173         >>> x.splitlines(True)
174         [adsfasdf\n, sadf\n, asdf\n, adf]
175 
176         S.splitlines([keepends]) -> list of strings
177 
178         Return a list of the lines in S, breaking at line boundaries.
179         Line breaks are not included in the resulting list unless keepends
180         is given and true.
181         """
182         return []
183 
184     def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
185         S.startswith(prefix[, start[, end]]) -> bool
186 
187         Return True if S starts with the specified prefix, False otherwise.
188 
189 
190     def strip(self, chars=None): # real signature unknown; restored from __doc__
191         S.strip([chars]) -> str
192 
193         Return a copy of the string S with leading and trailing
194 
195     def swapcase(self): # real signature unknown; restored from __doc__
196         """
197         大小写反转
198         S.swapcase() -> str
199 
200         Return a copy of S with uppercase characters converted to lowercase
201         and vice versa.
202         """
203         return ""
204 
205     def title(self): # real signature unknown; restored from __doc__
206         """
207         S.title() -> str
208 
209         Return a titlecased version of S, i.e. words start with title case
210         characters, all remaining cased characters have lower case.
211         """
212         return ""
213 
214     def translate(self, table): # real signature unknown; restored from __doc__
215         """
216         table=str.maketrans(alex,big SB)
217 
218         a=hello abc
219         print(a.translate(table))
220 
221         S.translate(table) -> str
222 
223         Return a copy of the string S in which each character has been mapped
224         through the given translation table. The table must implement
225         lookup/indexing via __getitem__, for instance a dictionary or list,
226         mapping Unicode ordinals to Unicode ordinals, strings, or None. If
227         this operation raises LookupError, the character is left untouched.
228         Characters mapped to None are deleted.
229         """
230         return ""
231 
232     def upper(self): # real signature unknown; restored from __doc__
233         """
234         S.upper() -> str
235 
236         Return a copy of S converted to uppercase.
237         """
238         return ""
239 
240     def zfill(self, width): # real signature unknown; restored from __doc__
241         """
242         原来字符右对齐,不够用0补齐
243         
244         S.zfill(width) -> str
245 
246         Pad a numeric string S with zeros on the left, to fill a field
247         of the specified width. The string S is never truncated.
248         """
249         return ""
str的方法

 

 

homework

技术分享
1 # 1:编写for循环,利用索引遍历出每一个字符
2 # msg=‘hello egon 666‘
3 
4 
5 msg=hello egon 666
6 
7 for i in range(len(msg)):
8     print(msg[i])
作业一
技术分享
1 # 2:编写while循环,利用索引遍历出每一个字符
2 # msg=‘hello egon 666‘
3 msg=hello egon 666
4 count = 0
5 
6 while count < len(msg):
7     print(msg[count])
8     count += 1
作业二
技术分享
1 # 3:
2 # msg=‘hello alex‘中的alex替换成SB
3 
4 msg=hello alex
5 
6 print(msg)
7 print("修改后:",msg.replace(alex, SB))
作业三
技术分享
 1 # 4:
 2 # msg=‘/etc/a.txt|365|get‘
 3 # 将该字符的文件名,文件大小,操作方法切割出来
 4 
 5 msg=/etc/a.txt|365|get
 6 msg_list = msg.split(|)
 7 print("""
 8   打印说明
 9 1.文件名:{}
10 2.大  小:{}
11 3.方  法:{}
12 """.format(msg_list[0], msg_list[1], msg_list[2]))
作业四
技术分享
1 # 编写while循环,要求用户输入命令,如果命令为空,则继续输入
2 
3 flag = True
4 while flag:
5     if len(input(">>>").strip()) != 0:
6         flag = False
7     continue
作业五
技术分享
 1 # 编写while循环,让用户输入用户名和密码,如果用户为空或者数字,则重新输入
 2 
 3 flag = True
 4 
 5 while flag:
 6     username = input(username:).strip()
 7     password = input(password:).strip()
 8     if len(username) != 0 and not username.isdigit():
 9         flag = False
10     continue
作业六
技术分享
1 # 编写while循环,让用户输入内容,判断输入的内容以alex开头的,则将该字符串加上_SB结尾
2 
3 while True:
4     s = input(">>>")
5     if s == q:
6         break
7     elif s.startswith(alex):
8         s+=_SB
9     print(s)
作业七
技术分享
 1 # 8.
 2 # 1.两层while循环,外层的while循环,让用户输入用户名、密码、工作了几个月、每月的工资(整数),用户名或密码为空,或者工作的月数不为整数,或者
 3 # 月工资不为整数,则重新输入
 4 # 2.认证成功,进入下一层while循环,打印命令提示,有查询总工资,查询用户身份(如果用户名为alex则打印super user,如果用户名为yuanhao或者wupeiqi
 5 # 则打印normal user,其余情况均打印unkown user),退出功能
 6 # 3.要求用户输入退出,则退出所有循环(使用tag的方式)
 7 flag = True
 8 
 9 
10 while flag:
11     username = input(用户名:).strip()
12     password = input(密码:).strip()
13     work_time = input(工作时间:).strip()
14     salary = input(工资:).strip()
15     if len(username) == 0 or len(password) == 0 or not work_time.isdigit() or not salary.isdigit():
16         continue
17     else:
18         while flag:
19             choose = input("1.查询工资\n2.查询身份\n3.退出\n>>>")
20             if choose == 1:
21                 input(%s的工资是%s元%(username, salary))
22             elif choose == 2:
23                 if username == alex:
24                     input(supper user)
25                 elif username == yuanhao or username == wupeiqi:
26                     input(normal user)
27                 else:
28                     input(unkown user)
29             elif choose == 3 or choose == q:
30                 flag = False
31             else:
32                 input("Error")
作业八

 

day14 python02---字符串