首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python基础篇 strings 01

Python基础篇 strings 01

作者头像
披头
发布2019-12-26 11:00:19
3990
发布2019-12-26 11:00:19
举报
文章被收录于专栏:datartisandatartisan

python基础, strings

获取字符修改字符?获取超出索引范围的字符迭代字符替换字符

获取字符
  • by index
In [1]: sampleStr = "Hello, this is a sample string"

In [2]: print( "Character at index 5 is : " , sampleStr[5] )
Character at index 5 is :  ,
  • by negative index
In [3]: sampleStr = "Hello, this is a sample string"
   ...:
   ...: print( "Last character in string : " , sampleStr[-1] )
   ...: print( "Second Last character in string : " , sampleStr[-2] )
   ...: print( "First character in string : " , sampleStr[ -len(sampleStr) ] )
Last character in string :  g
Second Last character in string :  n
First character in string :  H
修改字符?

由于字符串是不可变的,当我们试图改变字符串时,程序将返回错误

In [7]: sampleStr = "Hello, this is a sample string"

In [8]: sampleStr[5] = 's'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-a03ca5d20f4e> in <module>
----> 1 sampleStr[5] = 's'

TypeError: 'str' object does not support item assignment
获取超出索引范围的字符

当获取字符的索引超出字符串长度时,程序将抛出 IndexError 错误,所以,当我们使用索引获取字符时总是要先检查字符串的大小(长度)

In [9]: sampleStr = "Hello"
   ...:
   ...: #Handle Out Of Range Error by try / except
   ...: try :
   ...:     print( sampleStr[50] )
   ...: except IndexError:
   ...:     print ("Index : Out of range")
   ...:
Index : Out of range

In [10]: sampleStr = "Hello"
    ...:
    ...: # Check the size of string before accessing character by index
    ...: n = 50
    ...: if n < len(sampleStr) :
    ...:     print( sampleStr[50] )
    ...: else :
    ...:     print ("Index : Out of range")
    ...:
Index : Out of range
迭代字符
  • 使用 for 循环
In [11]: sampleStr = "Hello!!"
    ...:
    ...: print("**** Iterate over string using for loop****")
    ...:
    ...: for elem in sampleStr:
    ...:     print(elem)
    ...:
**** Iterate over string using for loop****
H
e
l
l
o
!
!
  • 使用 range()
In [12]: print("**** Iterate over string with index using range() ****")
    ...:
    ...: for i in range( len(sampleStr) ):
    ...:     print(sampleStr[i])
    ...:
**** Iterate over string with index using range() ****
H
e
l
l
o
!
!
  • 迭代字符串的一部分
In [13]: print("**** Iterate over a portion of string only ****")
    ...:
    ...: # Iterate over the first three elements of string
    ...: for elem in sampleStr[0:3:1] :
    ...:     print(elem)
    ...:
**** Iterate over a portion of string only ****
H
e
l
  • 跳跃式迭代
In [16]: print("**** Iterate over string  by skipping every 2nd characters ****")
    ...:
    ...: # Iterate over a string with 2 characters at a time
    ...: for elem in sampleStr[ : : 2] :
    ...:     print(elem)
    ...:
**** Iterate over string  by skipping every 2nd characters ****
H
l
o
!
  • 反向迭代、逆向迭代
In [17]: print("**** Iterate over string in reverse using slice operation****")
    ...:
    ...: for elem in sampleStr[ : :-1]:
    ...:     print(elem)
    ...:
**** Iterate over string in reverse using slice operation****
!
!
o
l
l
e
H
In [18]: print("**** Iterate over string in reverse****")
    ...:
    ...: i = len(sampleStr) - 1
    ...: while i >= 0 :
    ...:     print(sampleStr[i])
    ...:     i = i - 1
    ...:
**** Iterate over string in reverse****
!
!
o
l
l
e
H
print("**** Iterate over string in reverse using negative indexing****")    

i = 1 
while i <= len(sampleStr) :
    print(sampleStr[-i])
    i = i + 1 
替换字符

str.replace(old, new , count)

  • 替换所有指定字符
In [19]: mainStr = "Hello, This is a sample string"
    ...: '''
    ...: Replace all occurrences of given character or string in main string
    ...: '''
    ...: otherStr = mainStr.replace('s' , 'X')

In [20]: otherStr
Out[20]: 'Hello, ThiX iX a Xample Xtring'
  • 替换前 n 个指定字符
In [21]: mainStr = "Hello, This is a sample string"
    ...: '''
    ...: Replace First 2 occurrences of given character or string in main string
    ...: '''
    ...: otherStr = mainStr.replace('s' , 'XXXS', 2)

In [22]: otherStr
Out[22]: 'Hello, ThiXXXS iXXXS a sample string'
  • 替换多个指定的字符
In [23]: mainStr = "Hello, This is a sample string"
    ...:
    ...: '''
    ...: Replace a set of multiple sub strings with a new string in main string.
    ...: '''
    ...: def replaceMultiple(mainString, toBeReplaces, newString):
    ...:     # Iterate over the strings to be replaced
    ...:     for elem in toBeReplaces :
    ...:         # Check if string is in the main string
    ...:         if elem in mainString :
    ...:             # Replace the string
    ...:             mainString = mainString.replace(elem, newString)
    ...:
    ...:     return  mainString
    ...:
    ...: '''
    ...: Replace multiple characters / strings from a string
    ...: '''
    ...: # Replace all the occurrences of string in list by AA in the main list
    ...: otherStr = replaceMultiple(mainStr, ['s', 'l', 'a'] , "AA")

In [24]: otherStr
Out[24]: 'HeAAAAo, ThiAA iAA AA AAAAmpAAe AAtring'
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-06-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 乐享数据8090 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 获取字符
  • 修改字符?
  • 获取超出索引范围的字符
  • 迭代字符
  • 替换字符
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档