草庐IT

python字符串切片及常用方法

learning-striving 2023-04-15 原文

一、切片

切片:指对操作的对象截取其中一部分的操作,字符串、列表、元组都支持切片操作

语法:序列[开始位置下标:结束位置下标:步长] ,不包含结束位置下标数据,步长为选取间隔,正负均可,默认为1

举例如下:

str = 'abcdefg_a'
print(str[1:6:2], str[2:6], str[:3], str[3:], str[:])
print(str[::2], str[:-2], str[-6:-2], str[::-2], str[::-1])
print(str[-2:], str[2:-2], str[-2::-2], str[:-2:2], str[2:-2:2])

输出:
bdf cdef abc defg_a abcdefg_a
acega abcdefg defg ageca a_gfedcba
_a cdefg _fdb aceg ceg

二、常用方法

2.1 查找

查找字符串:即查找子串在字符串中的位置或出现的次数

  • find():检测某个字串是否包含在某个字符串中,若存在则返回该子串开始位置下标,否则返回-1
    • 语法:字符串序列.find(子串,开始位置下标,结束位置下标)
  • index():检测某个子串是否包含在某个字符串中,若存在则返回该子串开始位置下标,否则报异常
    • 语法:字符串序列.index(子串,开始位置下标,结束位置下标)
  • rfind():和find()功能相同,但查找方向为右侧开始,即返回子串最后出现位置
  • rindex():和index()功能相同,但查找方向为右侧开始,即返回子串最后出现位置
  • count():返回某个子串在字符串中出现的次数

举例如下:

str = 'abcdefg_a'
print('-------------------查找-------------------')
print(str.find('c'), str.find('fg', 2, ), str.find('a', 2), str.find('h'))
print(str.index('c'), str.index('fg', 2, ), str.index('a', 2))
print(str.find('a'), str.rfind('a'), str.index('a'), str.rindex('a'), str.count('a'))
print(str.index('h'))

输出:
-------------------查找-------------------
2 5 8 -1
2 5 8
0 8 0 8 2
ValueError: substring not found

2.2 修改

修改字符串:通过函数形式修改字符串中的数据

  • replace():替换
    • 语法:字符串序列.replace(旧子串,新子串,最大替换次数)
  • split():按指定字符分割字符串
    • 语法:字符串序列.split(分割字符,分割次数)  # 返回数据个数分割次数+1
  • join():用一个字符或子串合并字符串,即将多个字符串合并为一个新的字符串
    • 语法:字符或子串.join(多字符串组成的序列)
  • capitalize():将字符串第一个字符转为大写,转换后仅首字符大写,其余均小写
    • 语法:字符串序列.capitalize() 
  • title():将字符串每个单词首字母转为大写
  • lower():将字符串中大写转小写
  • upper():将字符串中小写转大写
  • swapcase():翻转字符串中大小写
  • partition('分隔符'):根据指定分隔符将字符串分割,返回三元元组,组成为左子串、分隔符、右子串
  • min(str):返回字符串str中最小字母
  • max(str):返回字符串str中最大字母
  • zfill(width):输出指定长度为width的字符串,右对齐,不足前面补0,超出指定长度则原样输出
  • lstrip():删除字符串左侧空格字符
  • rstrip():删除字符串右侧空格字符
  • strip():删除字符串两侧空格字符
  • ljust():字符串左对齐,并用指定字符(默认空格)填充至对应长度
    • 语法:字符串序列.ljust(长度,填充字符)
  • rjust():字符串右对齐,并用指定字符(默认空格)填充至对应长度
    • 语法:字符串序列.rjust(长度,填充字符)
  • center():居中对齐,并用指定字符(默认空格)填充至对应长度
    • 语法:字符串序列.center(长度,填充字符)

举例如下:

print('--------------修改--------------')
str1 = 'hello python and hello IT and hello world and hello YX !'
print(str1.replace('and','&&'))
print(str1.split('and'), str1.split('and', 2))
l = ['Hello', 'world', '!']
t = ('Hello', 'python', '!')
print('_'.join(l), ' '.join(t))  # 用下划线_和空格连接
print(str1.capitalize())  # 首字符转为大写,其余均小写
print(str1.title())  # 每个单词首字母转为大写
str2 = '   Hello World !   '
print(str2.lower(), str2.upper(), str2.swapcase())  # 大写转小写,小写转大写,翻转大小写
print(str2.partition('rl'), str2.partition('o'))  # 根据指定分隔符将字符串分割,返回三元元组
print(min(str2), max(str2), ord(min(str2)), ord(max(str2)))  # str2中最小为空格对应十进制32,最大为r对应114
print(str2.zfill(21))  # 输出指定长度为21的字符串,右对齐,不足前面补0,超出指定长度则原样输出
print(str2.lstrip(), str2.rstrip(), str2.strip())  # 清除字符串左、右、两边空格字符
str3 = 'hello!'
print(str3.ljust(13, '*'), str3.rjust(13, '*'), str3.center(14, '*'))

输出:
--------------修改--------------
hello python && hello IT && hello world && hello YX !
['hello python ', ' hello IT ', ' hello world ', ' hello YX !'] ['hello python ', ' hello IT ', ' hello world and hello YX !']
Hello_world_! Hello python !
Hello python and hello it and hello world and hello yx !
Hello Python And Hello It And Hello World And Hello Yx !
   hello world !       HELLO WORLD !       hELLO wORLD !   
('   Hello Wo', 'rl', 'd !   ') ('   Hell', 'o', ' World !   ')
  r 32 114
00   Hello World !  
Hello World !       Hello World ! Hello World !
hello!******* *******hello! ****hello!****

2.3 判断

  • startswith():检查字符串是否以指定子串开头,若是返回True,否则返回False,设置开始和就结束位置下标,则在指定范围内检查
    • 语法:字符串序列.startswith(子串,开始位置下标,结束位置下标)
  • endswith():检查字符串是否以指定子串结尾,是返回True,否则返回False,设置开始和就结束位置下标,则在指定范围内检查
    • 语法:字符串序列.endswith(子串,开始位置下标,结束位置下标)
  • isalpha():若字符串至少有一个字符并所有字符都是字母则返回True,否则返回False
  • isdigit():若字符串只包含数字则返回True否则返回False
  • isalnum():若字符串至少有一个字符且所有字符都是字母或数字则返回True,否则返回False
  • isspace():若字符串只包含空格,则返回True,否则返回False

举例如下:

print('---------------判断----------------')
str3 = 'hello!'
print(str3.startswith('he'), str3.startswith('she'), str3.startswith('he',2,))
print(str3.endswith('!'), str3.endswith('。'), str3.endswith('!', 2, 5))
print(str3.isalpha(),str3.isalnum(), str3.isdigit(), str3.isspace())

输出:
---------------判断----------------
True False False
True False False
False False False False

导航:http://xqnav.top/

有关python字符串切片及常用方法的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  4. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  5. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  6. ruby-on-rails - unicode 字符串的长度 - 2

    在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)

  7. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  10. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

随机推荐