Python字符串用法(二)

    科技2025-09-16  40

    基本操作(一)

    首字符大小写切换、反转 字符串首字符转大写、全部大小写转换、每个字符首字符大写等… str = "hello wOrd" 1) print(str.upper()) # HELLO WORD 返回大写字符串 2) print(str.lower()) # hello word 返回小写字符串 3) print(str.title()) # Hello Word 每个单词首字符转大写,其余小写 4) print(str.capitalize()) # Hello word 将字符串中单词的首字母转化为大写,其他字母全部转化为小写 5) print(str.swapcase()) # HELLO WoRD 大小写反转 判断字符串开头与结尾 startswith(“目标字符”):以…开头 endswith(“目标字符”): 以…结尾 startwith/endswith(“目标字符”,start,end):在指定范围内判断开始结尾的字符,start-end:包头不包尾 两者判断返回值为bool类型,True 或 False。建议在做判断时首尾去掉空格:字符串.strip() str ="Hello word" print(str.startswith("H")) # 判断以"H"大写,返回值:True print(str.endswith("h")) # 判断以"h"写,返回值:False print(str.startswith("e",1,6)) # 在一定范围内判断以"e"开头,返回值:True 统计 统字符出现的次数:string.count(“目标字符”) 统计范围内的次数:string.count(“目标字符”,start,end) str = "hello word" print(str.count("o")) # 2次 print(str.count("o",4,7)) # 指定范围统计数据, 1次 填充样式 length*“样式符号”:重复输出相同的符号填充 string.center():居中填充,打印输出字符,让字符串放在中间 name = "poppy" print(30*"-") # 重复展示30个 - print(name.center(30,"*")) # poppy居中展示
    Processed: 0.018, SQL: 8