wsxxz 发表于 2018-8-10 11:39:50

Python(四)字符串

  字符串的定义
  ·第一种方式:
  str1 = 'redhat'
  ·第二种方式:
  str2 = "redhat"
  ·第三种方式:
  str3 = """redhat"""
  转义符号
  \n   代表换行符
  \t    代表tab符
  \"    代表双引号本身
  \'   代表单引号本身
  >>> print "sunny,"ok""
  File &quot;<stdin>&quot;, line 1
  print &quot;sunny,&quot;ok&quot;&quot;
  ^
  SyntaxError: invalid syntax
  >>> print &quot;sunny,\&quot;ok\&quot;&quot;
  sunny,&quot;ok&quot;
  字符串类型转换
  str(obj) 将其他类型内容转换为字符串
  int(obj) 将字符串转换为为整数
  float(obj) 将字符串转换为浮点型
  long(obj) 将字符串转换为长整型
  字符串操作
  字符串属于序列,序列支持的操作如下:
  一、索引
  · 索引(s ):获取特定偏移的元素
  · 给出一个字符串,可输出任意一个字符,如果索引为负数,就是相当于从后向前数。
  >>> s='hello'
  >>> s
  'h'
  >>> s[-1]
  'o'
  >>> s+s
  'he'
  二、切片
  切片S提取对应的部分作为一个序列:
  ·上边界并不包含在内;
  ·如果没有给出切片的边界,切片的下边界默认为0,上边界为字符串的长度;
  ·扩展的切片S,其中i,j含义同上,k为递增步长;
  s[:]获取从偏移量为0到末尾之间的元素
  s获取从偏移量为1到末尾之间的元素
  >>> num='abcdefgh'
  >>> num
  'ab'
  >>> num
  'ace'
  >>> num[:]
  'abcdefgh'
  >>> num
  'bcdefgh'
  >>> num[::-1]         #表示倒序显示所有元素
  'hgfedcba'
  三、成员操作符(判断子串)
  判断一个字符串是不是属于s字符串
  >>> a='hello'
  >>> 'o' in a
  True
  >>> 'o' not in a
  False
  四、连接操作符
  >>> a='hello'
  >>> b='world'
  >>> a+b
  'helloworld'
  五、重复操作符
  >>> &quot;$&quot;*10          #将$重复显示10次
  '$$$$$$$$$$'
  >>> print &quot;#&quot;*10 + &quot;管理系统&quot; + &quot;#&quot;*10
  ##########管理系统##########
  
  内置函数
  一、计算长度
  >>> a='hello'
  >>> len(a)
  5
  二、取最大、最小
  In : max('1234')
  Out: '4'
  In : min('1234')
  Out: '1'
  三、枚举
  #可以同时遍历索引和遍历元素
  >>> s='hello'
  >>> for i,j in enumerate(s):
  ...   print i,j
  ...
  0 h
  1 e
  2 l
  3 l
  4 o
  四、比较
  cmp()
  五、zip
  >>> s='123'
  >>> s1='abc'
  >>> s2='ABC'
  >>> zip(s,s1,s2)
  [('1', 'a', 'A'), ('2', 'b', 'B'), ('3', 'c', 'C')]
  字符串常用操作
  []里的内容表示可要可不要
  str.capitalize()
  - 将字符串首字母大写,并返回新的首字母大写后的字符串;

  tr.center(width[,fillchar])
  - 返回一个长为width的新字符串,在新字符串中原字符居中,其他部分用fillchar指定的符号填充,未指定时通过空格填充。

  tr.count(sub[, start[, end]]) -> int
  - 返回sub在str中出现的次数,如果start与end指定,则返回指定范围内的sub出现次数。

  str.endswith(suffix[, start[, end]])
  - 判断字符串是否以suffix结束,如果start和end指定,则返回str中指定范围内str子串是否以suffix结尾,如果是,返回True;否则返回False
  str.startswith(prefix[, start[, end]])

  tr.find(sub[,start[,end]])
  - 判断sub是否在str中,存在返回索引值,不存在返回-1.
  str.index(sub[,start[,end]])
  - 与find方法函数功能相同,如果sub不存在时抛出ValueError异常;
  str.isalnum() //判断是否都是字母或数字
  str.isalpha() //判断是否都是字母
  str.isdigit() //判断是否都是数字
  str.islower() //判断是否都是小写
  str.isspace() //判断是否都是英文空格
  str.istitle() //判断是不是都是标题(有大小写)
  str.isupper() //判断是不是都为大写字母
  str.join(seq)
  - 以str作为分隔符,将序列seq中的所有元素合并为一个新的字符串。
  In : a='123'
  In : b='456'
  In : a.join(b)
  Out: '412351236'
  str.replace(old,new[,count])
  - 将str中的old字符串替换为new字符串,并将替换后的新字符串返回,如果count指定,则只替换前count个字符串
  In : s=&quot;h e llo&quot;
  In : s.replace(&quot; &quot;,&quot;&quot;)
  Out: 'hello'
  tr.split(])
  - 以sep字符串作为分割符对str进行切割,默认为空格;
  - maxsplit代表切割的此处
  In : a=&quot;admin redhat centos&quot;
  In : a.split()
  Out: ['admin', 'redhat', 'centos']
  str.strip()
  - 返回一字符串,将str中首尾包含指定的chars字符删除的字符串,未指定时,删除首尾的空格。
  str.lower() //将大写字母转换为小写
  str.upper() //将小写字母转换为大写
  str.ljust()
  -字符串对齐格式化字符串
  In : str='hello'
  In : str.ljust(30,'*')
  Out: 'hello*************************'
  str.rjust()
  -字符串对齐格式化字符串
  In : str='hello'
  In : str.rjust(30,'*')
  Out: '*************************hello'
  题目1:
  用户输入一个变量名,判断是否合法
  解答:
  方法一:运用字符常用操作的知识
  #!/usr/bin/env python
  # coding:utf-8
  &quot;&quot;&quot;
  变量名的命名规则:由数字、字母、_组成并且不能以数字开头
  &quot;&quot;&quot;
  while True:
  name=raw_input(&quot;输入一个变量名:&quot;)
  if name.isdigit():
  print &quot;变量名不合法(error 1)&quot;
  else:
  for i in name:
  if not(i.isalnum() or i == &quot;_&quot;):
  print &quot;变量名不合法(error 2)&quot;
  break
  else:
  print &quot;变量名合法&quot;
  方法二:使用string函数
  In : import string
  In : string.digits
  Out: '0123456789'
  In : string.letters
  Out: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  #!/usr/bin/env python
  # coding:utf-8
  &quot;&quot;&quot;
  变量名的命名规则:由数字、字母、_组成并且不能以数字开头
  &quot;&quot;&quot;
  import string
  while True:
  name=raw_input(&quot;输入一个变量名:&quot;)
  if name == string.digits:
  print &quot;变量名不合法(error 1)&quot;
  else:
  for i in name:
  if not(i in string.digits or i in string.letters or i == &quot;_&quot;):
  print &quot;变量名不合法(error 2)&quot;
  break
  else:
  print &quot;变量名合法&quot;
页: [1]
查看完整版本: Python(四)字符串