美文网首页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 String 方法详解三:字符串的联合与分割

    Python String 方法详解三:字符串的联合与分割 str.join(iterable) --...

  • 2018-04-11

    Python字符串切片操作知识详解(转载自脚本之家): 一:取字符串中第几个字符 print "Hello"[0]...

  • python元编程详解

    注:采转归档,自己学习查询使用 python元编程详解(1)python元编程详解(2)python元编程详解(3...

  • 字符串拼接详解

    1.使用 + 拼接字符串详解 2.使用StringBuilder拼接字符串详解 总结

  • python 字符串详解

    python 字符串 介绍字符串相关的:比较,截取,替换,长度,连接,反转,编码,格式化,查找,复制,大小写,分割...

  • Python字符串详解

    str本质 Python str的本质可以通过help命令查看 可以看到 str的本质是Python模块__bui...

  • python字符串详解

    字符串定义 字符串是由一个个字符组成的序列 使用成对的单引号或者双引号two_quote_str = 'hello...

  • Python 字符串详解

    字符串替换 字符串拼接 1.两个字符串拼接 2.打印拼接 字符串按照字符切割 字符串比较 字符串长度 字符串是否包...

  • 你真的知道Python的字符串是什么吗?

    在《详解Python拼接字符串的七种方式》这篇推文里,我提到过,字符串是程序员离不开的事情。后来,我看到了一个英文...

  • 你真的知道 Python的 字符串是什么吗?

    在《详解Python拼接字符串的七种方式》这篇推文里,我提到过,字符串是程序员离不开的事情。后来,我看到了一个英文...

网友评论

    本文标题:python字符串详解

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