字符串



1.创建字符串

 可以使用引号('或")来创建字符串

 eg:str = 'hello' str2 = "hello"






2.获取子字符串长度

 len() 方法返回字符串长度

 eg: len(str) # 5

 




3.访问字符串

 1.通过索引值:

  str[0] # h



 2.通过切片:

  str[1:-1] # ell



 3.for 循环:

  for s in str:print(s)



 4.while循环:

  start = 0

  while start<len(str):

    print(str[start])

   start += 1



4.字符串运算符

  str1 = 'hello' str2 = 'world'

  1. + # 字符串拼接

   eg: str1+str2 # helloworld

  2. * #重复输出该字符串 

   eg: str1*4 #hellohellohellohello

  3. [] # 通过索引获取字符串中字符

   eg: str[1] # e

  4.[:] # 截取字符串中的一部分

   eg:str[1:3] # el

  5.in # 成员运算符-如果给定的字符在字符串中返回True ,如果没有在里面则返回False

   eg: 'h'in str1 #True ; 'H'in str1 #False

   6.not in # 成员运算符-如果字符不在字符串中返回True ,如果在里面返回FALSE

   eg : 'H'not in str1 # True

  7.r/R #原始字符串 - 所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符

   eg: r' ' #

  



5.字符串格式化

  1. %方式

     %s 格式化字符串

    %d 格式化整数

   eg: '我是%s,今年%d岁' % ('花花',23) # 我是花花,今年23岁



  2. str.format()方式 使用{}占位符

   eg: In: '我是{},今年{}岁'.format('花花',23) out: 我是花花,今年23岁



In : '我是{0},今年{1}岁,{0}今天很高兴'.format('花花',23) out:我是花花,今年23岁,花花今天很高兴

   

      In: '我是{name},今年{age}岁,{name}今天很高兴'.format(name='花花',age=23) out:我是花花,今年23岁,花花今天很高兴




6.字符串内置函数

 1.字母处理
全部大写:str.upper()
全部小写:str.lower()
大小写互换:str.swapcase()
首字母大写,其余小写:str.capitalize()
首字母大写:str.title()
  
  eg:
str = 'hEllo wOrld'
print(str.upper()) # HELLO WORLD
print(str.lower()) # hello world
print(str.swapcase()) # HeLLO WoRLD
print(str.capitalize()) # Hello world
print(str.title()) # Hello World
  

2.字符串格式输出:

str.center(width[, fillchar])      # 获取固定长度,中间对齐,两边不够用fillchar补齐,默认空格补齐
str.rjust(width[, fillchar])       # 获取固定长度,右对齐,左边不够用fillchar补齐,默认空格补齐
str.ljust(width[, fillchar])       # 获取固定长度,左对齐,右边不够用fillchar补齐,默认空格补齐
str.zfill(width)            # 获取固定长度,原字符串右对齐,前面填充0
width -- 指定字符串长度.
fillchar -- 填充字符,默认为空格.

   eg:
str = 'hello world'
print(str.center(20)) # hello world
print(str.ljust(20,"*")) # hello world*********
print(str.rjust(20,'*')) # *********hello world
print(str.zfill(20)) # 000000000hello world


3.字符串搜索定位与替换:

str.count(self, sub, start=None, end=None) # 统计子字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置
str.find(self, sub, start=None, end=None) # 返回子字符串最后一次出现的位置,如果没有匹配项则返回-1。
str.rfind(self, sub, start=None, end=None) # 返回子字符串返回开始的索引值,否则返回-1。
str.index(self, sub, start=None, end=None) # 返回子字符串返回开始的索引值,否则抛出异常
str.rindex(self, sub, start=None, end=None) # 返回子字符串 sub 在字符串中最后出现的位置,如果没有匹配的字符串会报异常
str.replace(self, old, new, count=None) # 返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数count,则替换不超过 count次。

sub -- 指定检索的字符串
start -- 开始索引,默认为0。
end -- 结束索引,默认为字符串的长度

  eg:
str = 'study hard and make progress every day'
print(str.count('a',2,9)) # 1
print(str.find('a',9,12)) # 11
print(str.rfind('a')) # 36
print(str.index('a')) # 7
print(str.rindex('df')) # ValueError: substring not found index 和rindex未找到抛出异常
print(str.replace('a','ABC',2)) # study hABCrd ABCnd make progress every day



4.字符串去空格,去指定字符

str.strip(self, chars=None) # 移除字符串头尾指定的字符(默认为空格)
str.rstrip(self, chars=None) # 删除字符串末尾的指定字符(默认为空格)
str.lstrip(self, chars=None) # 删除字符串开头的指定字符(默认为空格)


chars -- 移除字符串指定的字符

str = ' 【helloworld】 '
str1 = '【helloworld】'
print(str.strip()) # 【helloworld】
print(str.lstrip()) # 【helloworld】
print(str.rstrip()) # 【helloworld】
print(str1.strip('】')) # 【helloworld


5.字符串联合与分割

str.join(self, iterable) # 用于将序列中的元素以指定的字符连接生成一个新的字符串
str.partition(self, sep) # 将字符串分割成3部分,第二部分是自己
str.split(self, sep=None, maxsplit=-1) # 指定分隔符对字符串进行切片,如果参数maxsplit有指定值,则仅分隔 maxsplit个子字符串
str.rsplit(self, sep=None, maxsplit=-1)          # 指定分隔符从右边对字符串进行切分
str.splitlines(self, keepends=None) #按照行(' ', ' ', ')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符
sep -- 分隔符,默认为所有的空字符,包括空格、换行( )、制表符( )等。
maxsplit ---分割次数

str = 'hello world welcome'
str1 = 'welcome 【 to china'
list1 = ['welcom','to','china']

print(str.split()) # ['hello', 'world', 'welcome']
print(str.rsplit(' ',1)) # ['hello world ', 'welcome']
print(str1.split('【')) # ['welcome ', ' to china']
print(str.partition('wor')) # ('hello ', 'wor', 'ld welcome')
new_str ='_'.join(list1) # welcom_to_china
print(new_str)


6.字符串条件判断:

str.endswith(self, suffix, start=None, end=None) # 判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False
str.startswith(self, prefix, start=None, end=None) # 检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False
str.isalnum() # 检测字符串是否由字母和数字组成
str.isalpha() # 方法检测字符串是否只由字母组成
str.isdecimal() # 检查字符串是否只包含十进制字符
str.isdigit() # 方法检测字符串是否只由数字组成
str.isnumeric() # 检测字符串是否只由数字组成。这种方法是只针对unicode对象
str.isidentifier() # 判断字符串是否是合法的标识符
str.islower() # 检测字符串是否由小写字母组成
str.isprintable() # 判断字符串所包含的字符是否全部可打印
str.isspace() # 检测字符串是否只由空格组成
str.istitle() # 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写
str.isupper() # 检测字符串中所有的字母是否都为大写

eg:
str = 'helloworld'
str1 = 'hello123'
str2= '1234'
str3 = 'Hello World'
str4 = ' '
print(str.endswith('ld')) # Ture
print(str.startswith('hell')) # Ture
print(str1.isalnum()) #Ture
print(str.isalpha()) # Ture 字符串间有空格为FALSE
print(str2.isdecimal()) # True
print(str2.isdigit()) # True
print(str2.isnumeric()) #True str.isnumeric False
print(str.isidentifier()) # True
print('23sdfa'.isidentifier()) # False
print(str.islower()) #True
print(str.isupper()) #False
print(str3.istitle()) # True
print(str4.isspace()) # True
print(str.isprintable()) # True




7.字符串编码解码:


str.encode(self, encoding='utf-8', errors='strict') # 以指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案
str.decode(self, encoding='UTF-8',errors='strict') # 以 encoding 指定的编码格式解码字符串

encoding -- 要使用的编码,如: UTF-8

str = 'hello world'
en_str = str.encode(encoding='utf-8')
print(en_str,type(en_str)) # b'hello world' <class 'bytes'>

de_str = en_str.decode(encoding='utf-8')
print(de_str,type(de_str)) # hello world <class 'str'>



8.字符串三引号

三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符

str = """
hellowrold
welcome to chengdu
"""
print(str)

输出结果:

hellowrold

welcome to chengdu

原文地址:https://www.cnblogs.com/lovuever/p/6572672.html