python基础, strings
获取字符修改字符?获取超出索引范围的字符迭代字符替换字符
In [1]: sampleStr = "Hello, this is a sample string"
In [2]: print( "Character at index 5 is : " , sampleStr[5] )
Character at index 5 is : ,
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
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
!
!
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'
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'