一文了解字符串常用方法

一文了解字符串常用方法

center()

方法center通过在两边添加填充字符(默认为空格)让字符串居中

>>> "The Middle by Jimmy Eat World".center(39)
'    The Middle by Jimmy Eat World '
>>> "The Middle by Jimmy Eat World".center(39, "*")
'*****The Middle by Jimmy Eat World*****'
count()
s = 'reresrhffd'
# ‘r’的个数
print(s.count('r')) # 3
# 切片0到3‘r’的个数
print(s.count('r',0,3))  # 2
endswith()
s = 'reresrhffd'
# 字符串是否以‘d'结尾
print(s.endswith('d'))  # True
# 切片0到5,包前不包后,是否以’s‘结尾
print(s.endswith('s',0,5))  # True
find()

方法 find 在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回 -1

>>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$', 1) # 只指定了起点
20
>>> subject.find('!!!')
16
>>> subject.find('!!!', 0, 16) # 同时指定了起点和终点
-1
index()

同find()

s = 'reresrhffd'
# 寻找’s'的位置
print(s.index('s'))  # 4
# 在切片2到7寻找‘h’
print(s.index('h',2,7))# 6
# 指定位置未找到则报错
print(s.index('a'))# 报错
join()

join方法,其作用与split相反,用于合并序列的元素,所合并序列的元素必须都是字符串

>>> seq = [1, 2, 3, 4, 5]
>>> sep = '+'
>>> sep.join(seq) # 尝试合并一个数字列表
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: sequence item 0: expected string, int found
>>> seq = ['1', '2', '3', '4', '5']
>>> sep.join(seq) # 合并一个字符串列表
'1+2+3+4+5'
>>> dirs = '', 'usr', 'bin', 'env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print('C:' + '\\'.join(dirs))
C:\usr\bin\env
lower()

方法lower返回字符串的小写版本,可用于忽略大小写

>>> 'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'
title()

词首大写

print('sssss  dcc ghhhh'.title()) # Sssss  Dcc Ghhhh

确定单词边界的方式可能导致结果不合理

>>> "that's all folks".title()
"That'S All, Folks"
# 另一种方法是使用模块string中的函数capwords 。
>>> import string
>>> string.capwords("that's all, folks")
That's All, Folks"
replace()

方法 replace 将指定子串都替换为另一个字符串,并返回替换后的结果

>>> 'This is a test'.replace('is', 'eez')
'Theez eez a test'
split()

split是一个非常重要的字符串方法,其作用与join相反,用于将字符串拆分为序列

>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>> 'Using the default'.split()
['Using', 'the', 'default']

# 两个参数
s = "hello,TZ"
print(s.split("l", 1))  #['he', 'lo,TZ']
print(s.split("l", 2))  #['he', '', 'o,TZ']

如果没有指定分隔符,将默认在单个或多个连续的空白字符(空格、制表符、换行符等)处进行拆分

strip()

方法strip将字符串开头和末尾的空白**(但不包括中间的空白)**删除,并返回删除后的结果

>>> '   internal whitespace is kept    '.strip()
'internal whitespace is kept'
  • 还可在一个字符串参数中指定要删除哪些字符
  • 这个方法只删除开头或末尾的指定字符,因此中间的星号未被删除
>>> '*** SPAM * for * everyone!!! ***'.strip(' *!')
'SPAM * for * everyone'
lstrip()
s = "  hello,TZ  "
print(s.lstrip())      #hello,TZ  移除左边
rstrip()
s = "  hello,TZ  "
print(s.rstrip())      #  hello,TZ移除右边
ljust()

内容左对齐,右侧填充

s = 'reresrhffd'
# 左对齐,右侧填充
print(s.ljust(20),'r')   # reresrhffd           r
# 左对齐,右侧*填充
print(s.ljust(20,'*'))   # reresrhffd**********
rjust()
print('helloword'.rjust(20, '+'))
# +++++++++++helloword
capitalize()
s = "asfgffd"
print(s.capitalize())        #Asfgffd  第一个字母大写

s = "asfgffd , Asdffgg"
print(s.capitalize())        #Asfgffd , asdffgg    第一个字母大写,其余大写变小写
casefold()
s = "asfgffd , Asdffgg"
print(s.casefold())          #asfgffd , asdffgg     全部变小写
translate()
  • 方法 translate与replace一样替换字符串的特定部分,但不同的是它只能进行单字符替换。
  • 这个方法的优势在于能够同时替换多个字符,因此效率比 replace 高。
  • 使用translate前必须创建一个转换表。这个转换表指出了不同Unicode码点之间的转换关系。要创建转换表,可对字符串类型str调用方法maketrans,这个方法接受两个参数:两个长度相同的字符串,它们指定要将第一个字符串中的每个字符都替换为第二个字符串中的相应字符
>>> table = str.maketrans('cs', 'kz')
# 创建转换表后,就可将其用作方法 translate 的参数。
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
  • 调用方法maketrans 时,还可提供可选的第三个参数,指定要将哪些字母删除
>>> table = str.maketrans('cs', 'kz', ' ')
>>> 'this is an incredible test'.translate(table)
'thizizaninkredibletezt'
partition()

将字符串分割为前,中(sep),后三部分,返回元组

s = 'reresrhffd'
print(s.partition('s'))  # ('rere', 's', 'rhffd')
isalnum()

是否是字母和数字

s = 'reresrhffd'
print(s.isalnum()) # True
s1 = '12'
print(s1.isalnum())  # True
isalpha()

是否是字母

s = 'reresrhffd'
print(s.isalpha()) # True
s1 = '12'
print(s1.isalpha())  # False
isdigit()

是否是数字

s = 'reresrhffd'
print(s.isdigit()) # False
s1 = '12'
print(s1.isdigit())  # True
islower()

是否小写

s = 'reresrhffd'
print(s.islower()) # True
isspace()

是否空格

s = 'reresrhffd'
print(s.isspace()) # False
# 一个空格False
s1 = ''
print(s1.isspace()) # False
# 一个以上为True
s2 = '   '
print(s2.isspace())  # True
isupper()

是否大写

s = 'reresrhffd'
print(s.isupper()) # False
s1 = 'Rdsgd'
print(s1.isupper()) # False
s2 = 'RADASF'
print(s2.isupper()) # True
isinstance()

判断是否为字符串

x = 'abc'
y = 123
print(isinstance(x, str))
# True
print(isinstance(y, str))
# False

s = ['Hello', 'World', 18, 'Apple', None]
s1 = [i for i in s if isinstance(i,str)]
print(s1) # ['Hello', 'World', 'Apple']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LocalDateTime常用方法有: 1. of():根据指定的年、月、日、时、分、秒创建一个LocalDateTime对象。例如,LocalDateTime.of(2023, 3, 5, 10, 20, 30)可以创建一个表示2023年3月5日10:20:30的LocalDateTime对象。 2. now():获取当前的日期和时间的LocalDateTime对象。 3. getYear()、getMonth()、getDayOfMonth()等方法:获取LocalDateTime对象中的年、月、日等具体值。 4. plusXXX()、minusXXX()方法:在LocalDateTime对象上进行日期和时间的加减操作。例如,plusDays(1)可以将日期加1天。 5. withXXX()方法:修改LocalDateTime对象中的某个字段的值,返回一个新的LocalDateTime对象。例如,withYear(2024)可以将年份修改为2024年。 6. format()方法:将LocalDateTime对象格式化为指定的字符串。可以使用DateTimeFormatter类来指定日期时间的格式。 7. compareTo()方法:比较两个LocalDateTime对象的大小。 8. isBefore()、isAfter()方法:判断两个LocalDateTime对象的先后顺序。 9. toLocalDate()、toLocalTime()方法:将LocalDateTime对象转换为LocalDate对象或LocalTime对象。 这些方法可以帮助我们对日期和时间进行各种操作和处理。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [LocalDateTime 的常用方法一文轻松解决掉你的烦恼!](https://blog.csdn.net/m0_69237510/article/details/129981759)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [Scala - 时间工具类 LocalDateTime 常用方法整理](https://blog.csdn.net/BIT_666/article/details/130082525)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值