python字符串长度的获取,大小写转化,去除收尾空格和所定字母

字符串长度获取

Python 提供了len()函数来计算,并返回字符串的长度,即字符串中单个元素的个数。其基本语法如下:

 
  1. length = len(target_string)

其中:

  • target_string: 目标字符串变量;

  • length: 保存字符串长度的变量;

  • len: 获取字符串长度的语法关键词。

下面给出了具体的使用示例:

 
  1. # coding=utf-8
  2. # 创建一个字符串变量,获取其长度并打印出来
  3. color = 'It is red'
  4. length = len(color)
  5. print (length)
  6. # 直接在len函数中引入字符串内容获得其长度,然后打印出来
  7. print(len('This is a circle!'))

输出结果:

 
  1. 9
  2. 17

注意: 从输出结果可以看到,空格也占一个字符元素的位置。

大小写转换

Python 提供了upper()lower()方法,来对字符串进行大小写转换。其中,upper()会将字符串中的所有字符都转换为大写,lower()则将所有字符转换为小写。除此之外,Python 还贴心的提供了title()方法,将字符串所有单词的首字母变成大写,而其他字母依然小写。各个方法的具体语法如下:

 
  1. # 将源字符串转换为大写并存入upper_string变量
  2. upper_string = source_string.upper()
  3. # 将源字符串转换为小写并存入lower_string变量
  4. lower_string = source_string.lower()
  5. # 将源字符串每个词首字母转换为大写并存入title_string变量
  6. title_string = source_string.title()

其中,source_string为待处理的源字符串。具体使用示例如下:

 
  1. # coding=utf-8
  2. # 创建一个字符串say_hello
  3. say_hello = 'Dear my Daughter'
  4. # 使用upper()方法对say_hello字符串进行处理
  5. upper_say_hello = say_hello.upper()
  6. # 使用lower()方法对say_hello字符串进行处理
  7. lower_say_hello = say_hello.lower()
  8. # 使用title()方法对say_hello字符串进行处理
  9. title_say_hello = say_hello.title()
  10. # 打印输出四个字符串
  11. print (say_hello+"\n")
  12. print (upper_say_hello+"\n")
  13. print (lower_say_hello+"\n")
  14. print (title_say_hello+"\n")

输出结果:

 
  1. Dear my Daughter
  2. DEAR MY DAUGHTER
  3. dear my daughter
  4. Dear My Daughter

注意: 由上述打印结果可以看出,上述方法的调用,并不会对原始的 say_hello字符串产生影响,转换后的字符串会存入新的变量中。

去除字符串首尾空格

Python 提供了strip()方法,可以去除字符串两侧(不包含内部)全部的空格。使用该方法,也可以通过指定参数,去除两侧指定的特定字符。
 

注意:在指定参数时,如果参数是多个字符,则该方法会将多个字符逐个去比对,进行删除(区分大小写),直到首尾两侧没有匹配的字符为止。但是,该方法对字符串中间的字符没有影响。

其基本语法如下:

 
  1. strip_string1 = source_string.strip()
  2. string_strip2 = source_string.strip(target_char)

其中:

  • source_string:待处理的源字符串;

  • strip_string1strip_string2:处理后的字符串;

  • target_char:需要从源字符串首尾去除的特定字符。

具体使用示例如下:

 
  1. # coding = utf-8
  2. # 创建一个字符串hello_world
  3. hello_world = ' **The world ** is big!* '
  4. # 利用strip()方法处理hello_world字符串
  5. blank_hello_world = hello_world.strip()
  6. char_hello_world = hello_world.strip('TH *')
  7. # 打印输出转换后的字符串
  8. print(blank_hello_world)
  9. print(char_hello_world)

输出结果:

 
  1. **The world ** is big!*
  2. he world ** is big!

输出结果分析:

  • 从第一行打印结果可以看到,strip()方法去除了源字符串首尾的所有空格,但是并没有去除字符串中间的空格;

  • 从第二行打印结构可以看出,strip()方法将源字符串首尾所有空格、* 以及字符T去掉了,而源字符串中头部的h因为是小写并没有去除。

  • 例题解决:

  •  

     

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超级鲁滨逊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值