Python 高级变量类型 --- 字符串

字符串

1,字符串的定义

  • 字符串 就是 一串字符 ,是编程语言中表示文本的数据类型
  • 在Python中可以使用一对双引号"或者一对单引号'定义一个个字符串
    • 虽然可以是使用\"或者\'做字符串的转义,但是在实际开发中:
      • 如果字符串内部需要使用",可以使用'定义字符串
      • 如果字符串内部需要使用',可以使用"定义字符串
  • 可以使用 索引 获取一个字符串中 指定位置的字符 ,索引技术从0开始
  • 也可以使用for循环遍历字符串中每一个字符
    大多数编程语言都是使用"来定义字符串

    str_test = "Hello Python"
    for i in str_test:
        print(i)
        
    H
    e
    l
    l
    o
    
    P
    y
    t
    h
    o
    n
    
    # 1,统计字符串长度
    length = len(str_hello)
    print(length)
    
    11
    
    # 2,统计某一个小字符串出现的次数
    frequency_a = str_hello.count("llo")
    print(frequency_a)
    
    2
    
    # 如果收搜一个不存在的字符串,则显次数为0
    frequency_b = str_hello.count("abc")
    print(frequency_b)
    
    0
    
    # 3,某一个字符串出现的位置
    location_a = str_hello.index("llo")
    print(location_a)
    
    2
    
    # 如果字符串不存在,则程序报错
    location_b = str_hello.index("abc")
    print(location_b)

字符串的常用操作

  • ipython3中定义一个字符串,例如str_hello = "hello hello"
  • 输入str_hello.按下TAB键,ipython3会提示字符串 能够使用的方法如下:

    In [1]: str_hello = "hello hello"
    
    In [2]: str_hello.
        str_hello.capitalize   str_hello.expandtabs   str_hello.isalpha      str_hello.isnumeric    str_hello.ljust        str_hello.rfind        str_hello.split        str_hello.translate
        str_hello.casefold     str_hello.find         str_hello.isascii      str_hello.isprintable  str_hello.lower        str_hello.rindex       str_hello.splitlines   str_hello.upper
        str_hello.center       str_hello.format       str_hello.isdecimal    str_hello.isspace      str_hello.lstrip       str_hello.rjust        str_hello.startswith   str_hello.zfill
        str_hello.count        str_hello.format_map   str_hello.isdigit      str_hello.istitle      str_hello.maketrans    str_hello.rpartition   str_hello.strip
        str_hello.encode       str_hello.index        str_hello.isidentifier str_hello.isupper      str_hello.partition    str_hello.rsplit       str_hello.swapcase
        str_hello.endswith     str_hello.isalnum      str_hello.islower      str_hello.join         str_hello.replace      str_hello.rstrip       str_hello.title

提示:正是因为python内置提供的方法足够多,才使得在开发时,能够针对字符串进行更加灵活的操作。

1,判断类型

||||

猜你喜欢

转载自www.cnblogs.com/xiaoqshuo/p/9467241.html
今日推荐