python第三节:Str字符串类型(8)

str.strip([chars])

返回原字符串的副本,移除其中的前导和末尾字符。 chars 参数为指定要移除字符的字符串。 如果省略或为 None,则 chars 参数默认移除空白符。

注意:参数chars 并非作为一个整体,而是会移除参数值的所有组合。

在移除字符串前后的指定字符时,遇到不在参数组合中的字符时即停止。

例子:

#

arg1 = '   spacious   '

arg2 = 'www.example.com'

arg3 = '#....... Section 3.2.1 Issue #32 .......'



print(arg1.strip())

print(arg2.strip('cmowz.'))

print(arg3.strip('.#! '))

结果:

spacious

example

Section 3.2.1 Issue #32

str.rstrip([chars])

和str.strip([chars])类似,区别在于str.rstrip([chars])至移除末尾的字符。

返回原字符串的副本,移除其中的末尾字符。 chars 参数为指定要移除字符的字符串。 如果省略或为 None,则 chars 参数默认移除空白符。  chars 参数并非移除指定单个后缀;而是会移除参数值的所有组合:

例子:

#

arg1 = '   spacious   '

arg2 = 'mississippi'

arg3 = 'Monty Python'

arg4 = 'Python Monty Python'



print(arg1.rstrip())

print(arg2.rstrip('ipz'))

print(arg3.rstrip(' Python'))

print(arg3.strip(' Python'))

print(arg4.rstrip(' Python'))

print(arg4.strip(' Python'))

结果:

   spacious

mississ

M

M

Python M

M

str.startswith(prefix[, start[, end]])

判断字符串以什么字符开始,如果以prefix开始则返回true否则返回false。

start和end是起止位置。不包含end。

例子:

arg1 = 'spacious'



print(arg1.startswith('sp'))

print(arg1.startswith('sp',0,1))

print(arg1.startswith('sp',0,2))

print(arg1.startswith('ci',3,4))

print(arg1.startswith('ci',3,5))

结果:

True

False

True

False

str.title()

返回原字符串的标题版本,其中每个单词第一个字母为大写,其余字母为小写。

注意:将连续的字母组合视为单词。如缩写US会变成Us

例子:

arg1 = 'spacious world ni '

arg2 = 'spacious world UK US '



print(arg1.title())

print(arg2.title())

结果:

Spacious World Ni

Spacious World Uk Us

str.upper()

str.upper()将能够区分大小写的字符变为大写。

返回原字符串的副本,其中所有区分大小写的字符均转换为大写。 请注意如果 s 包含不区分大小写的字符或者如果结果字符的 Unicode 类别不是 "Lu" (Letter, uppercase) 而是 "Lt" (Letter, titlecase) 则 s.upper().isupper() 有可能为 False。

例子:

arg1 = 'spacious world ni '

arg2 = 'spacious world UK US '

arg3 = '你好hello world'



print(arg1.upper())

print(arg2.upper())

print(arg3.upper())

结果:

SPACIOUS WORLD NI

SPACIOUS WORLD UK US

你好HELLO WORLD

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值