Python学习08--字符串运算

    技术2022-07-13  79

    Python学习08--字符串运算

    Python学习08判断字符串相等==is 字符串拼接+*+=*= 判断字符是否在字符串中innot in 字符串表示格式化输出 %保留原格式 r获取字符串中特点位置字符 []字符串截取 [:]逆序与步长 [::-1] 字符串内置函数大小写转换查找相关替换编码与解码判断开头与结尾字符串内容判断字符串分隔与截取 学习视频:b站 【千锋教育】Python 900集 书籍: Head First Python(中文版) 学习总结笔记,侵删

    Python学习08

    判断字符串相等

    ==

    ==比较内容

    s1 = "abc" s2 = "abc" s3 = "abcd" print(s1==s2) print(s1==s3)

    is

    is比较地址

    s1 = input(); s2 = input(); print(s1 is s2)

    字符串拼接

    +

    +号将运算符两边的字符串进行拼接,赋予=号左边的变量

    s1 = "hello " s2 = "world" s3 = s1 + s2 print(s3)

    *

    *号将字符串进行若干次复制

    s1 = "*" s2 = s1 * 5 print(s2)

    +=

    s1 = "hello " s2 = "world" s1 += s2 print(s1)

    *=

    s1 = "*" s1 *= 5 print(s1)

    判断字符是否在字符串中

    in

    in判断是否在该字符串中,返回True或False

    s1 = "hello" print("h" in s1)

    not in

    当要判断的字符不在字符串中时返回True,否则返回False

    s1 = "hello" print("h" not in s1)

    字符串表示

    格式化输出 %

    print("%s name is %s and my grade is %d" %("my","bob", 100))

    保留原格式 r

    print("a\na") print("********") print(r"a\na")

    获取字符串中特点位置字符 []

    s1 = "hello" print(s1[1])

    字符串截取 [:]

    包前不包后,前后均可省略,若前省略,则默认从0开始。若后省略,则默认为取到字符串末尾。值可为负数。

    s1 = "hello" print(s1[0:3])

    逆序与步长 [::-1]

    该数字可表示步长,小于0逆序

    s1 = "hello" print(s1[::-1])

    字符串内置函数

    大小写转换

    1.capitalize() 将字符串的首字母进行大写

    s1 = "hello world and python" s2 = s1.capitalize() print(s2)

    2.title() 每个单词的首字母均大写

    s1 = "hello world and python" s2 = s1.title() print(s2)

    3.upper() 将所有小写转成大写

    s1 = "hello world and python" s2 = s1.upper() print(s2)

    4.lower()将所有大写转成小写

    s1 = "hello world and python" s2 = s1.upper() s3 = s2.lower() print(s2) print(s3)

    查找相关

    1.find(str,beg=0,end=len(string)) 检测str是否包含在字符串中,若指定范围,则检测是否在指定范围内,在则返回索引值,否则返回-1. 2.index(str,beg=0,end=len(string)) 与find()相同,但未找到会报一个异常

    替换

    1.replace(old,new [,max]) 把str1替换为str2,如果max指定,则替换次数不超过max

    编码与解码

    1.编码 encode(encoding=‘UTF-8’,errors=‘stricts’) 以encoding指定的编码格式编码字符串,如果出错默认报一个ValueError的异常,除非errors指定的是’ignore’或‘replace’ 2.解码 decode(encoding=‘UTF-8’)

    判断开头与结尾

    1.startswitch() 判断字符串是否以xxx开头,返回布尔值 2.endswitch() 判断字符串是否以xxx结尾,返回布尔值

    字符串内容判断

    1.isalpha() 若字符串至少有一个字符,且所有字符都是字母,则返回True,否则返回False 2.isdigit() 若字符串只包含数字,则返回True,否则返回False 3.isnumeric() 若字符串只包含数字字符,则返回True,否则返回False 4.isspace() 若字符串只包含空白,则返回True,否则返回False

    字符串分隔与截取

    1.join(seq) 以指定字符串作为分隔符,将seq中所有的元素的字符串表示合并为一个新的字符串

    s1 = "#".join("abc") print(s1)

    2.lstrip() 截掉字符串左边的空格或指定字符 3.rstrip() 截掉字符串右边的空格或指定字符 4.split(str="",num=string.count(str)) 以分割str字符串,将分割后的字符串保存在列表中,若num有指定值,则仅截取num+1个子字符串

    Processed: 0.010, SQL: 9