美文网首页Python
python字符串详解

python字符串详解

作者: Shawn_Shawn | 来源:发表于2020-09-18 01:26 被阅读0次

    字符串定义

    • 字符串是由一个个字符组成的序列

    • 使用成对的单引号或者双引号

      two_quote_str = 'hello python'
      one_quote_str = "hello python"
      
    • 成对的三引号,保留字符串中的全部格式信息

      # 会保留换行符,制表符
      three_quote_str = '''languages:
        1.python
        2.java
        3.golang
        4.c++
      '''
      

    字符串的操作

    基本操作(序列通用功能)

    1. 索引访问

      str = "12345678"
      print(str[0])
      print(str[2])
      print(str[8]) # IndexError: string index out of range
      print(str[-1])
      print(str[-8])
      print(str[-9]) # IndexError: string index out of range
      
    2. 拼接运算符

      a = "1"
      b = "2"
      c = a + b
      print(c) # "s12"
      
      a = "1"
      b = 2
      c = a + b # TypeError: can only concatenate str (not "int") to str
      
    3. 重复运算符

      c = a * b * b
      print(c) # 1111
      
      c = a * 1.2 # TypeError: can't multiply sequence by non-int of type 'float'
      print(c)
      
    4. 切片运算符

      str = "12345678"
      print(str) # 12345678
      print(str[:]) # 12345678
      print(str[0:]) # 12345678
      print(str[:1]) # 1
      print(str[1:5]) # 2345
      print(str[0:-1:2]) # 1357
      
    5. 成员运算符

      name = "shawn"
      print("s" in name) # True
      print("sh" in name) # True
      print("Sh" in name) # False 区分大小写
      print("a" not in name) # False
      print("  s" in name) # False
      # print([1, 3, 4] not in name) # TypeError: 'in <string>' requires string as left operand, not list
      print(1 in name) # TypeError: 'in <string>' requires string as left operand, not int
      
    6. 常用函数

      print(len(name))
      print(name[len(name) - 1]) # 访问最后一个序列元素
      print(sorted(name)) # ['a', 'h', 'n', 's', 'w']
      
    7. 遍历

      for c in name :
          print(c)
      

    字符串特有的操作

    1. 一些常用的函数(不会改变原字符串的值)

      操作 含义
      upper() 字符串中所有字母转大写
      lower() 字符串中所有字母转小写
      capitalize() 字符串中的首字母大写
      title() 字符串中的所有单词的首个字母转化为大写
      rstrip() lstrip() strip() 去掉(左或右或两边)的空格
      split() 按照指定字符串分隔字符
      isdigit() 是不是数字类型
      find() 查找。返回下标
      replace(old,new) 把所有的old子串替换成new子串
      message = "my name is shawn, i'm 20 year old"
      print(message.capitalize()) # My name is shawn, i'm 20 year old
      print(message.title()) # My Name Is Shawn, I'M 20 Year Old
      print(message) # "my name is shawn, i'm 20 year old"
      
      print(message.replace("my", "your")) # your name is shawn, i'm 20 year old
      print(message) # "my name is shawn, i'm 20 year old"
      
    2. 注意点:字符串不可变,一旦生成则内容不变

      message = "my name is shawn, i'm 20 year old"
      print(message.capitalize()) # My name is shawn, i'm 20 year old
      print(message.title()) # My Name Is Shawn, I'M 20 Year Old
      print(message) # "my name is shawn, i'm 20 year old"
      
      message[0:2] = "your" #TypeError: 'str' object does not support item assignment
      
      

      如何改变?只能重新赋值

      message = "your name is shawn, i'm 20 year old"
      

    字符串练习

    1. 判断是否有元音字母

      AEIOU_STR = 'aeiou'
      
      
      def vowel_count(s):
          count = 0;
          for c in s:
              if c in AEIOU_STR + AEIOU_STR.upper():
                  count += 1;
      
          return count
      
      
      print(vowel_count("hello world"))
      
    2. 判断是否是回文字符串

      names = open("E:\\python_learning\\note\\names.txt")
      
      
      def is_palindrome_recursion(name):
          if len(name) <= 1:
              return True
          else:
              if name[0] != name[-1]:
                  return False
              else:
                  return is_palindrome_recursion(name[1:-1])
      
      
      def is_palindrome(name):
          left = 0
          right = len(name) - 1;
          while left < right:
              if name[left] != name[right]:
                  return False;
              left += 1
              right -= 1
          return True
      
      
      for c in names:
          c = c.strip().lower();
          if is_palindrome_recursion(c):
              print(c)
      
      names.close()
      
    3. 判断字符串是否是升序排列

      names = open("E:\\python_learning\\note\\names.txt")
      
      
      def is_ascending(name):
          temp = name[0]
          for n in name:
              if n < temp:
                  return False
              temp = n
          return True
      
      
      for c in names:
          c = c.strip().lower();
          if is_ascending(c):
              print(c)
      
      names.close()
      
    4. 模板字符串

      str_format = "my name is {}, i'm {} years old!".format("shawn", 20)
      print(str_format) # my name is shawn, i'm 20 years old!
      
      import math
      
      print("PI is {}".format(math.pi)) # PI is 3.141592653589793
      print("PI is {:.4f}".format(math.pi)) # PI is 3.1416
      print("PI is {:9.4f}".format(math.pi)) # PI is    3.1416
      print("PI is {:< 9.4f}".format(math.pi)) # PI is  3.1416
      
    5. 正则表达式

      import re
      
      names = open("E:\\python_learning\\note\\names.txt")
      
      p = "(c.a)"
      for c in names:
          c = c.strip().lower()
          result = re.search(p, c)
          if result:
              print("name in {}".format(c))
      
      names.close()
      

    names.txt

    相关文章

      网友评论

        本文标题:python字符串详解

        本文链接:https://www.haomeiwen.com/subject/rcrdyktx.html