0
点赞
收藏
分享

微信扫一扫

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

转角一扇门 2024-01-19 阅读 7

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

举报

相关推荐

0 条评论