Introducing to Python Text Sequence Type — str

Strings are mutable sequences of Unicode code points.
They are written in the following ways:

Single quote string :
>>> myString1 = 'allow embedded "double" quotes'
>>> myString1
'allow embedded "double" quotes'

Double quote string :
>>> myString2 = "allows embedded 'single' quotes"
>>> myString2
"allows embedded 'single' quotes"

Triple quote string :
>>> myString3 = '''Three single quotes''',"""Three double quotes"""
>>> myString3
('Three single quotes', 'Three double quotes')

String Methods:

str.capitalize

str.casefold

str.swapcase

 

str.islower

str.isupper

str.lower

str.upper

str.count

str.encode

str.expandtabs

str.replace

str.startswith

str.endswith

 

 

str.find

str.rfind

str.index

str.rindex

str.format

str.format_map

 

 

str.isdigit

str.isalnum

str.isalpha

str.isdecimal

str.isnumeric

str.isidentifier

 

 

str.isprintable

str.isspace

str.istitle

str.title

str.ljust

str.rjust

str.center

 

str.lstrip

str.strip

 

 

str.maketrans

str.translate

 

 

str.partition

str.rpartition

str.join

 

str.rsplit

str.split

str.splitlines

 

str.zfill

 

 

 


 

str.capitalize() - Return a capitalized version of the string with its first character capitalized and the rest lowercased.
>>> str.capitalize('danbrother')
'Danbrother'
 

str.casefold() - Return a version of the string for caseless comparisons.
>>> str.casefold('DANBROTHER')
'danbrother'
 

str.center(width[, fillchar])Return the string centered in a string of length width.  Padding is done using the specified fill character (default is a space).
>>> myString = 'DANBROTHER'
>>> myString.center(20,'*')
'*****DANBROTHER*****'


str.count(sub[, start[, end]])Return the number of non-overlapping occurrences of substring in the string.
>>> myString = 'aBCaBCaBCaBC'
>>> myString
'aBCaBCaBCaBC'
>>> myString.count('aBC')
4
>>> myString.count('aBC',3,9)
2


str.encode(encoding="utf-8", errors="strict")Encoding the string using the codec registered for encoding. Default encoding is ‘utf-8’. Errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
>>> myEncode = '測試'
>>> myEncode
'測試'
>>> myEncode.encode(encoding="utf-8",errors="strict")
b'\xe6\xb8\xac\xe8\xa9\xa6'
>>> myDecode = b'\xe6\xb8\xac\xe8\xa9\xa6'
>>> myDecode
b'\xe6\xb8\xac\xe8\xa9\xa6'
>>> myDecode.decode(encoding="utf-8",errors="strict")
'測試'

 

str.endswith(suffix[, start[, end]])Return True is the string ends with the specified suffix, False otherwise.
>>> myString = 'DANBROTHER'
>>> myString.endswith('D')

False
>>> myString.endswith('R')
True
>>> myString.endswith('N',0,3)
True

 

str.expandtabs(tabsize=8)Return a copy of the string where all tab characters are expanded using spaces. If tab size is not given, a tab size of 8characters is assumed.
>>> myString = 'Dan\tBrother'
>>> myString.expandtabs(4)
'Dan Brother'
>>> myString.expandtabs()
'Dan     Brother'

 

str.find(sub[, start[, end]])Return the lowest index in the string where substring is found. Retur-1 if substring is not found.
>>> myString = 'DanBrother'
>>> myString
'DanBrother'
>>> myString.find('B')
3
>>> myString.find('Brother')
3
>>> myString.find('Dan')
0
>>> myString.find('x')
-1
>>> myString.find('O')
-1
>>> myString.find('o')
5


str.format(*args, **kwargs)Return a formatted version of the string using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}').

>>> fruits = '{0}, {1}, {2}, {0}'
>>> fruits.format('apple','banana','guava')
'apple, banana, guava, apple'
>>> myString = '{4}, {3}, {2}, {1}, {0}'
>>> myString
'{4}, {3}, {2}, {1}, {0}'
>>> myString.format(*'12345')
'5, 4, 3, 2, 1'

>>> myString = '{:<30} \n {:>30} \n {:^30} \n {:*^30}'
>>> print(myString.format('Left Aligned','Right Aligned','Centered','Centered'))
Left Aligned                  
                  Right Aligned
            Centered          
***********Centered***********

 

str.format_map(mapping)Return a formatted version of the string using substitutions from mapping. The substitutions are identified by braces ('{' and '}').
>>> name = 'DanBrother'
>>> country = 'Taiwan'
>>> myString = 'My name is {name} and I live in {country}.'
>>> myString.format_map(vars())
'My name is DanBrother and I live in Taiwan.'

>>> value = {'name':'DanBrother','country':'Taiwan'}
>>> myString = 'My name is {name} and I live in {country}.'
>>> myString.format_map(value)
'My name is DanBrother and I live in Taiwan.'

 

str.index(sub[, start[, end]])Similar to str.find(sub[, start[, end]]), but raise ValueError when the substring is not found.
>>> myString = 'DanBrother'
>>> myString
'DanBrother'
>>> myString.index('B')
3
>>> myString.index('Brother')
3
>>> myString.index('Dan')
0
>>> myString.index('x')
Traceback (most recent call last):
  File "<pyshell#467>", line 1, in <module>
    myString.index('x')
ValueError: substring not found

>>> myString.index('O')
Traceback (most recent call last):
  File "<pyshell#469>", line 1, in <module>
    myString.index('O')
ValueError: substring not found

>>> myString.index('o')
5

str.isalnum()Return True if all characters in the string are alphanumeric and there is at least one character in the string, False otherwise.

>>> '123456'.isalnum()
True
>>> 'a12345'.isalnum()
True
>>> 'abcdef'.isalnum()
True
>>> 'abc#12'.isalnum()
False
>>> '!12345'.isalnum()
False

str.isalpha()Return True if all characters in the string are alphabetic and there is at least one character in the string, False otherwise.
>>> 'abcdef'.isalpha()
True
>>> 'AbcDef'.isalpha()
True
>>> 'a12b34'.isalpha()
False
>>> 'abcde#'.isalpha()
False

 

str.isdecimal()Return True if there are only decimal characters in the string, False otherwise.
>>> '123456'.isdecimal()
True
>>> '12345a'.isdecimal()
False
>>> '12345#'.isdecimal()
False
>>> '12 456'.isdecimal()
False
>>> '12.456'.isdecimal()

 

str.isdigit()Return True if all characters in the string are digits and there is at least one character in the string, False otherwise.
>>> '123456'.isdigit()
True
>>> '12345a'.isdigit()
False
>>> '12345#'.isdigit()
False
>>> '12 456'.isdigit()
False
>>> '12.456'.isdigit()

 

str.isidentifier()Return True if the string is a valid identifier according to the language definition.
>>> 'DanBrother'.isidentifier()
True
>>> 'DanBrother123'.isidentifier()
True
>>> 'DanBrother_123'.isidentifier()
True
>>> '123456'.isidentifier()
False
>>> 'DanBrother#123'.isidentifier()
False
>>> 'DanBrother!123'.isidentifier()
False

str.islower()Return True if all cased characters in the string are lowercase and there is at least one cased character in the string, False otherwise.
>>> str.islower('danbrother')
True
>>> str.islower('Danbrother')
False


str.isnumeric()Return True if there are only numeric characters in the string, False otherwise.
>>> str.isnumeric('0123456789')
True
>>> str.isnumeric('0123a56789')
False
>>> str.isnumeric('0.123456789')
False
>>> str.isnumeric('0_23456789')
False

 

str.isprintable()Return True if all characters in the string are considered printable or the string is empty, False otherwise.
>>> str.isprintable('DanBrother')
True
>>> str.isprintable('Dan\tBrother')
False
>>> str.isprintable('Dan\nBrother')
False

 

str.isspace()Return True is all characters in the string are whitespace and there is at least one character in the string, False otherwise.
>>> str.isspace(' ')
True
>>> str.isspace('   ')
True
>>> str.isspace('')

False
>>> str.isspace(' D ')
False
>>> str.isspace(' . ')
False

 

str.istitle()Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise.
>>> str.istitle('Dan Brother Is From Taiwan.')
True
>>> str.istitle('Dan Brother is from taiwan.')
False

 

str.isupper()Return True if all cased characters in the string are uppercase and there is at least one cased character in the string, False otherwise.
>>> str.isupper('DANBROTHER')
True
>>> str.isupper('DANbROTHER')
False

 

str.join(iterable)Return a string which is the concatenation of the strings in the iterable.
>>> text = 'DANBROTHER'
>>> text2 = '-'.join(text)
>>> text2
'D-A-N-B-R-O-T-H-E-R'

>>> fruit_list=["apple","banana","guava"]
>>> print(fruit_list)
['apple', 'banana', 'guava']
>>> print('\n'.join(fruit_list))
apple
banana
guava

 

str.ljust(width[, fillchar])Return the string left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is space)
>>> myString = 'DANBROTHER'
>>> myString.ljust(30)
'DANBROTHER                    '

>>> myString.ljust(30,'*')
'DANBROTHER********************'
>>> myString.ljust(30,'-')
'DANBROTHER--------------------'


str.lower()Return a copy of the string converted to lowercase.
>>> str.lower('DANBROTHER')
'danbrother'
>>> str.lower('DanBrother')
'danbrother'


str.lstrip([chars])Return a copy of the string with leading whitespace removed. If chars is given and not None, remove characters in chars instead.
>>> myString = '  DANBROTHER    '
>>> myString.lstrip()
'DANBROTHER    '

>>> myString = '***DANBROTHER***'
>>> myString.lstrip('*')
'DANBROTHER***

>>> myString = 'WHICHDANBROTHER'
>>> myString.lstrip('WHICH')
'DANBROTHER'


str.maketrans(x[, y[, z]])Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

>>> x = 'abcdefg'
>>> y = 'ABCDEFG'
>>> z = 'ZZZZZZZ'
>>> myString = 'this is a demo for maketrans YYYZZYYY'
>>> myTrans1 = str.maketrans(x,y)
>>> myString.translate(myTrans1)
'this is A DEmo For mAkEtrAns YYYZZYYY'

>>> myTrans2 = str.maketrans(x,y,z)
>>> myString.translate(myTrans2)
'this is A DEmo For mAkEtrAns YYYYYY'
 

str.partition(sep)Search for the separator sep in the string, and return the part before it, the separator itself, and the part after it.  If the separator is not found, return the string and two empty strings.
>>> myString = 'this is a demo of string partition'
>>> myPartition1 = myString.partition('demo')
>>> myPartition1
('this is a ', 'demo', ' of string partition')
>>> type(myPartition1)
<class 'tuple'>

>>> myPartition2 = myString.partition('test')
>>> myPartition2
('this is a demo of string partition', '', '')

 

str.replace(old, new[, count])Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
>>> myString1 = 'this is a test of string replacement'
>>> myReplacement = myString1.replace('test','demo')
>>> myReplacement
'this is a demo of string replacement'

>>> myString2 = 'this is a test test of string replacement'
>>> myReplacement = myString2.replace('test','demo',1)
>>> myReplacement
'this is a demo test of string replacement'

 

str.rfind(sub[, start[, end]])Return the highest index in the string 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.
>>> myString = 'this is a demo demo of string rfind'
>>> myRfind = myString.rfind('demo')
>>> myRfind
15
>>> myRfind = myString.rfind('test')
>>> myRfind
-1
 

str.rindex(sub[, start[, end]]) Like str.rfind() but raise ValueError when the substring is not found.
>>> myString = 'this is a demo demo of string rindex'
>>> myRindex = myString.rindex('demo')
>>> myRindex
15
>>> myRindex = myString.rindex('test')
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    myRindex = myString.rindex('test')
ValueError: substring not found

 

str.rjust(width[, fillchar]) Return the string right-justified in a string of length width. Padding is done using the specified fill character (default is a space).
>>> myString = 'DANBROTHER'
>>> myString.rjust(30)
'                    DANBROTHER'
>>> myString.rjust(30,'*')
'********************DANBROTHER'
>>> myString.rjust(30,'-')
'--------------------DANBROTHER'
 

str.rpartition(sep) Search for the separator sep in the string, start at the end of the string, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and the string.
myString = 'this is a demo of demo string rpartition'
>>> myRpartition1 = myString.rpartition('demo')
>>> myRpartition1
('this is a demo of ', 'demo', ' string rpartition')
>>> type(myRpartition1)
<class 'tuple'>
>>> myRpartition2 = myString.rpartition('test')
>>> myRpartition2
('', '', 'this is a demo of demo string rpartition')


str.rsplit(sep=None, maxsplit=-1)Return a list of the words in the string, using sep as the delimiter string, starting at the end of the string and working to the front.  If maxsplit is given, at most maxsplit splits are done.  If sep is not specified, any whitespace string is a separator.
>>> myString = 'this is a demo of string rsplit'
>>> myRsplit = myString.rsplit()
>>> myRsplit1 = myString.rsplit()
>>> myRsplit1
['this', 'is', 'a', 'demo', 'of', 'string', 'rsplit']

>>> myRsplit2 = myString.rsplit("r")
>>> myRsplit2
['this is a demo of st', 'ing ', 'split']

>>> myRsplit3 = myString.rsplit(" ",3)
>>> myRsplit3
['this is a demo', 'of', 'string', 'rsplit']

 

str.split(sep=None, maxsplit=-1)Return a list of the words in the string, using sep as the delimiter string.  If maxsplit is given, at most maxsplit splits are done.  If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
>>> myString = 'this is a demo of string split'
>>> mysplit1 = myString.split()
>>> mysplit1
['this', 'is', 'a', 'demo', 'of', 'string', 'split']

>>> mysplit2 = myString.split("r")
>>> mysplit2
['this is a demo of st', 'ing split']

>>> mysplit3 = myString.split(" ",3)
>>> mysplit3
['this', 'is', 'a', 'demo of string split']

 

str.splitlines([keepends])Return a list of the lines in the string, breaking at line boundaries.  Line breaks are not included in the resulting list unless keepends is given and true.
>>> myString = 'this\nis\na\ndemo\nof\nstring\nsplitlines'
>>> myString.splitlines()
['this', 'is', 'a', 'demo', 'of', 'string', 'splitlines']
>>> myString.splitlines(keepends=True)
['this\n', 'is\n', 'a\n', 'demo\n', 'of\n', 'string\n', 'splitlines']

 

str.startswith(prefix[, start[, end]])Return True if the string starts with the specified prefix, False otherwise. With optional start, test the string beginning at that position.  With optional end, stop comparing the string at that position. prefix can also be a tuple of strings to try.
>>> myString = 'this is a demo of string startwith'
>>> myString.startswith('this')
True
>>> myString.startswith('s',3)
True
>>> myString.startswith('s',1)
False

 

str.strip([chars])Return a copy of the string with leading and trailing whitespace removed.  If chars is given and not None, remove characters in chars instead.
>>> myString = '  DANBROTHER    '
>>> myString.strip()
'DANBROTHER'
>>> myString = '***DANBROTHER***'
>>> myString.strip('*')
'DANBROTHER'
>>> myString = 'WHICHDANBROTHER'
>>> myString.strip('WHICH')
'DANBROTHER'

 

str.swapcase()Return a copy of the string with uppercase characters converted to lowercase and vice versa.
>>> myString = 'THIS is A demo OF string SWAPCASE'
>>> myString.swapcase()
'this IS a DEMO of STRING swapcase'


str.title()Return a titlecased version of the string, i.e. words start with title case characters, all remaining cased characters have lower case.
>>> myString = 'this is a demo of string title'
>>> myString.title()
'This Is A Demo Of String Title'

 

str.translate(table)Return a copy of the string in which each character has been mapped through the given translation table.  The table must implement lookup/indexing via __getitem__,  for instance a dictionary or list, mapping Unicode ordinals to Unicode ordinals, strings, or None.  If this operation raised LookupError, the character is left untouched.  Characters mapped to None are deleted.
>>> myString = 'this is b cfmo oe string trbnslbtion'
>>> myDict = {ord('a'):'b', ord('b'):'a', ord('c'):'d', ord('d'):'c', ord('e'):'f', ord('f'):'e'}
>>> myDict
{97: 'b', 98: 'a', 99: 'd', 100: 'c', 101: 'f', 102: 'e'}
>>> myString.translate(myDict)
'this is a demo of string translation'

 

str.upper()Return a copy of the string converted to uppercase.
>>> myString = 'this is a demo of string uppercase'
>>> myString.upper()
'THIS IS A DEMO OF STRING UPPERCASE'

 

str.zfill(width)Pad a numeric string with zeros on the left, to fill a field of the specified width.  The string is never truncated.
>>> myString1 = "123456789"
>>> myString1.zfill(12)
'000123456789'

>>> myString2 = "12.50"
>>> myString2.zfill(6)
'012.50'

>>> myString3 = 'this is a demo of string zfill'
>>> myString3.zfill(40)
'0000000000this is a demo of string zfill'

 

 

[Reference]

https://docs.python.org/3/library/stdtypes.html#bytes.decode
https://docs.python.org/3/library/string.html#formatstrings

 

arrow
arrow
    文章標籤
    Python
    全站熱搜

    DanBrother 發表在 痞客邦 留言(0) 人氣()