python3 字符串屬性(一)


python3 字符串屬性

1 >>> a='hello world'
2 >>> dir(a)
3 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
1、S.capitalize() -> str   把字符串的第一個字符大寫
1 >>> a='hello world'
2 >>> a.capitalize()
3 'Hello world'

 

2、S.center(width[, fillchar]) -> str 返回一個原字符串居中,並使用空格填充至長度width 的新字符串
1 >>> a.center(15)
2 '  hello world  '

 

3、S.count(sub[, start[, end]]) -> int 返回str 在S 里面出現的次數,
1 >>> a='hello world'
2 >>> a.count('l',3)
3 2
4 >>> a.count('l',3,8)
5 1

 

4、S.casefold() 將字符串所有字符改為小寫(涉及到其他語言)
     S.lower()將字符串所有字符改為小寫
1 >>> a='HELLO WORLD'
2 >>> a.casefold()
3 'hello world'
4 >>> a
5 'HELLO WORLD'
6 >>> a.lower()
7 'hello world'
8 >>> a
9 'HELLO WORLD'

 

5、字符串編解碼

{
字符串在Python內部的表示是unicode編碼,因此,在做編碼轉換時,通常需要以unicode 作為中間編碼,即先將其他編碼的字符串解碼(decode)成unicode,再從unicode編(encode) 成另一種編碼。但是,Python 2.x的默認編碼格式是ASCII,就是說,在沒有指定Python源碼編碼 格式的情況下,源碼中的所有字符都會被默認為ASCII碼。也因為這個根本原因,在Python 2.x中 經常會遇到UnicodeDecodeError或者UnicodeEncodeError的異常。


原則

decode early, unicode everywhere, encode late,即:在輸入或者聲明字符串的時候, 盡早地使用decode方法將字符串轉化成unicode編碼格式;然后在程序內使用字符串的時候統一使用 unicode格式進行處理,比如字符串拼接、字符串替換、獲取字符串的長度等操作;最后,在輸出字符 串的時候(控制台/網頁/文件),通過encode方法將字符串轉化為你所想要的編碼格式,比如utf-8等。
https://segmentfault.com/a/1190000002966978
}
S.encode(encoding='utf-8', errors='strict') -> bytes 以encoding指定的編碼格式對字符串進行編碼,輸出的字節不是字符串,類型不同,屬性不同。


6.  S.endswith(suffix[, start[, end]]) -> bool
    
    Return True if S ends with the specified suffix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    suffix can also be a tuple of strings to try.

  

  S.startswith(prefix[, start[, end]]) -> bool
    
    Return True if S starts with the specified prefix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    prefix can also be a tuple of strings to try.

 1 >>> a='hello world!'
 2 >>> a.endswith('!')
 3 True
 4 >>> a.endswith('o',0,5)
 5 True
 6 >>> a.startswith('h')
 7 True
 8 >>> a.startswith('w',6)
 9 True
10 >>> a.startswith('hello')
11 True

 

 

7、 S.expandtabs(tabsize=8) -> str  把字符串的tab字符(\t)轉化為空格,如不指定tabsize,默認為8個空格

1 >>> a='hello world'
2 >>> a.expandtabs()
3 'hello world'
4 >>> a='\t hello world \t'
5 >>> a.expandtabs()
6 '         hello world    '
7 >>> a.expandtabs(tabsize=2)
8 '   hello world  '

 

8、S.find(sub[, start[, end]]) -> int   檢測sub是否在字符串中,如果在則返回index,否則返回-1,start,end為可選參數,決定范圍。(返回左側第一個)

 

  S.rfind(sub[, start[, end]]) -> int  (返回右側第一個)
    
    Return the highest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.

1 >>> a='hello world'
2 >>> a.find('h')
3 0
4 >>> a.find('h',1,3)
5 -1
6 >>> a.find('o',1,4)
7 -1
8 >>> a.find('o',1,5)
9 4

9、

S.index(sub[, start[, end]]) -> int     沒有找到返回ValuueError錯誤        (返回左側第一個)

Like S.find() but raise ValueError when the substring is not found.   沒有找到返回 -1

 

S.rindex(sub[, start[, end]]) -> int          (返回右側第一個)
    
    Like S.rfind() but raise ValueError when the substring is not found.

 

 

1 >>> a
2 'hello world'
3 >>> a.index('ll')
4 2
5 >>> a.index('lll')
6 Traceback (most recent call last):
7   File "<stdin>", line 1, in <module>
8 ValueError: substring not found

 

10、S.isalnum() -> bool  Return True if all characters in S are alphanumeric

  都是字母和數字字符返回True,否則返回False

>>> a.isalnum()
False
>>> a='123#$":,./'
>>> a.isalnum()
False
>>> a='123'
>>> a.isalnum()
True
>>> a='123a'
>>> a.isalnum()
True
>>> a='123a('
>>> a.isalnum()
False

 

11、S.isalpha() -> bool  Return True if all characters in S are alphabetic

 判斷字符串是否為字母

>>> a='123'
>>> b='123a'
>>> c='abc'
>>> a.isalpha()
False
>>> b.isalpha()
False
>>> c.isalpha()
True

  

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM