Python字符基本操作技巧分享


Python编程语言是一款功能强大的面向对象的计算机程序语言。其强大的优点可以帮助我们在实际编程中实现许多功能需求。今天我们就在这里先为大家介绍一下有关Python字符的基本内容。

一. Python字符的表示

用单引号或双引号构成字符串。

  1. “abc” \  
  2. ‘def’ 

表示一个字符串,而“abc”+“def”是两个字符串连接在一起,两者不一样。““” “”“中间可以为任意长的字符串

二.Python字符操作

1.大小写转换

  1. s.capitalize() #字符串s首写字母大写  
  2. s.lower() #全部变成小写  
  3. s.upper() #全部变成大写  
  4. s.swapcase() #大小写互换  
  5. len(s) #得到字符串的大小 

2.查找子串

  1. s.find(substring,[start[,end]]) 找到,返回索引值,找不到,返还-1  
  2. s.rfind(substring,[start[,end]]) 反向查找  
  3. s.index(substring,[start[,end]]) 与find()类似,如果找不到substring,就产生一个  
  4. ValueError的异常  
  5. s.rindex(substring,[start[,end]]) 反向查找  
  6. s.count(substring,[start[,end]]) 返回找到substring的次数 

3.格式化字符串

用法 s% < tuple> tuple表示一个参数列表,把tuple中的每一个值用字符串表示,表示的格 式有s来确定。

  1. s.ljust(width) 左对齐,如果width比len(s)大,则后面补空格。否则返回s。  
  2. s.rjust(width) 右对齐   
  3. s.center(width) 居中  
  4. s.lstrip() 去掉左边的空白字符  
  5. s.rstrip() 去掉右边的空白字符   
  6. s.lstrip() 去掉两边的空白字符 

 4. Python字符的合并和分解

合并:s.join(words)

words是一个含有字符串的tuple或list。join用s作为分隔符将words中的字符串连接起 来,合并为一个字符串。

例:

  1. >>> “+”.join([”hello”,”my”,”friedn”])  
  2. ‘hello+my+friedn’ 

分解:

  1. s.split(words) 

words是一个字符串,表示分隔符。split的操作和join相反。将s分解为一个list。

例:

  1. >>> “hello my fried”.split(” “)  
  2. [’hello’, ‘my’, ‘fried’]  

以上就是对Python字符的相关介绍。

评论关闭