There are already many on the Internet , Do it yourself , Deepen the impression .

dir

dir Will return a list of built-in methods and properties , Use string 'a,b,cdefg' Test it

dir('a,b,cdefg')

Get a list

['__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']

A string that starts with a double bottom horizontal is an internal method or a private method . The rest is the string method that can be used .

str.capitalize()

title case

In:'a,b,cdefg'.capitalize()
Out: 'A,b,cdefg'

str.casefold()

Make all letters lowercase , And lower similar ,lower Only English letters are supported A~Z, however casefold You can turn non English into lowercase .

In:'B,b,cdEfg'.casefold()
Out: 'b,b,cdefg' In:'B,b,cdEfg'.lower()
Out: 'b,b,cdefg'

official :

str.casefold()

Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'casefold() converts it to "ss".

The casefolding algorithm is described in section 3.13 of the Unicode Standard.

New in version 3.3.

In:'ß'.lower()
Out: 'ß' In:'ß'.casefold()
Out: 'ss'

str.center(width[, fillchar])

According to the given character and Total width centered . such as , Width is 5 String ‘11111’ According to the given character ‘r’ And total width 8, It is shown that :5 Two original characters centered ,'r' fill , The length is 8 String .

In:''.center(8,'r')
Out: 'r11111rr'

str.count(substartend)

The number of substrings in the original string .

sub -- Substring to search for

start -- Where the string starts searching , No default 0

end -- Where the string ends the search , Don't fill in as the last

In:'r11111rr'.count('',1,5)
Out[39]: 4

str.encode(encoding="utf-8"errors="strict")

encoding -- Encoding mode

errors -- Wrong solution . The default is 'strict', It's a coding error that causes a UnicodeError. Others may be worth 'ignore'--‘ ’, 'replace'--‘?’, 'xmlcharrefreplace'-- Extensible markup language replacement , 'backslashreplace'-- Backslash instead of as well as codecs.register_error() All values registered .


' The party '.encode('ascii')
Traceback (most recent call last):


File "<ipython-input-52-eb91b915d522>", line 1, in <module>
' The party '.encode('ascii')


UnicodeEncodeError: 'ascii' codec can't encode character '\u515a' in position 0: ordinal not in range(128)

' The party '.encode('ascii','replace')
Out[48]: b'?' ' The party '.encode('ascii','ignore')
Out[49]: b'' ' The party '.encode('ascii','xmlcharrefreplace')
Out[50]: b' The party ' ' The party '.encode('ascii','backslashreplace')
Out[51]: b'\\u515a'

str.endswith(suffixstartend)

If the string contains the specified suffix, return True, Otherwise return to False.

suffix -- Substring

start -- The starting position in a long string , Default 0

end -- End position in long characters , Default last

'B,b,cdEfg'.endswith('g')
Out[54]: True 'B,b,cdEfg'.endswith('Efg')
Out[55]: True 'B,b,cdEfg'.endswith('Ef')
Out[56]: False 'B,b,cdEfg'.endswith('Ef',1,8)
Out[57]: True

str.expandtabs(tabsize=8)

hold Tab--‘\t’ Change to a space character of other length ,'\t' The default is 8, Here is an example of the official website :

'01\t012\t0123\t01234'.expandtabs()
Out[101]: '01 012 0123 01234' '01\t012\t0123\t01234'.expandtabs(16)
Out[102]: '01 012 0123 01234'

str.find(str, beg=0, end=len(string))

Check if there is a substring in the string str ,beg( Start ) To end( end ) If it contains substrings , Then return to the beginning ( The smallest ) Index value , Otherwise return to -1. The default is 0 And finally .

'B,b,cdEfcg'.find('c',6,9)
Out[106]: 8 'B,b,cdEfcg'.find('c')
Out[107]: 4 'B,b,cdEfcg'.find('h')
Out[108]: -1

str.rfind(str, beg=0, end=len(string))

Usage and str.find Agreement , This one gets the end of ( maximal ) Index value .

str.format(*args**kwargs)

String formatting , adopt {} Instead of the traditional %.*arg Represents an immutable parameter -- Tuples ,**kwargs Represents a variable parameter -- Dictionaries

1. Indexes

{} Inside is the index ,0 Corresponding format The first element in .

' I {} A good man , you {} A good man !'.format(' yes ',' No ')
Out[111]: ' I am a good person. , You're not a good person !'
' I {1} A good man , you {0} A good man !'.format(' yes ',' No ')
Out[112]: ' I'm not a good person , You are very kind !' l = [' yes ',' No ']
' I {0[0]} A good man , you {0[1]} A good man !'.format(l)
Out[118]: ' I am a good person. , You're not a good person !'

2. keyword

' I { I } A good man , you { you } A good man !'.format( I =' yes ', you =' No ')
Out[121]: ' I am a good person. , You're not a good person !'

3. fill

'{0:*<10}'.format(' The party ') # The total length of 10, The string is on the left 
Out[127]: ' The party *********' '{0:*>10}'.format(' The party ') # The total length of 10, The string is on the right
Out[128]: '********* The party '
'{0:*^10}'.format(' The party ') # The total length of 10, String center 
Out[129]: '**** The party *****'

4. Precision and base

'{0:.2f}'.format(1/3)
Out[132]: '0.33' '{0:b}'.format(8) # Binary system
Out[133]: '' '{0:o}'.format(8) # octal
Out[134]: '' '{:,}'.format(111111111111111) # Kilo format
Out[135]: '111,111,111,111,111'

str.format_map(mapping)

And str.format(**mapping) similar , The difference lies in format_map Just use the dictionary , Instead of copying one . Here's an official example , among Default yes dict A subclass of .

class Default(dict):
def __missing__(self, key):
return key
'{name} was born in {country}'.format_map(Default(name='Guide')) Out[]: 'Guide was born in country'

str.index(str, beg=0, end=len(string))

And str.find similar , The difference lies in ,index If you can't find the character you want to find , You'll get ValueError, and find Then return to -1.

'asdfghjkhl'.find('i')
Out[]: - 'asdfghjkhl'.index('i')
Traceback (most recent call last): File "<ipython-input-25-af5de9246bb5>", line , in <module>
'asdfghjkhl'.index('i') ValueError: substring not found

str.rindex(str, beg=0, end=len(string))

Usage and str.rindex Agreement , This one gets the end of ( maximal ) Index value .

str.isalum()

If the string has at least one character , And if all the characters are letters or numbers, return True, Otherwise return to False.

'asdfghjkhl'.isalnum()
Out[26]: True 'asdfg.. hjkhl'.isalnum()
Out[27]: False

str.isalpha()

If the string has at least one character , If all characters are letters or Chinese characters, return True, Otherwise return to False.

str.isdecimal()     str.isdigit()     str.isnumeric()

3 All of them are to determine whether a string is a numeric character

The difference :

str.isdecimal()   On the surface : str It's Arabic numerals 123456 This is True, It's Chinese characters and numbers , The Roman number is False, According to the ‘’ No ‘’ Digital b" " by Error.

str.isdigit() In addition to Chinese characters, the number is False, The other numbers are True, Including single byte numbers b" ".

str.isnumeric() Except for one byte numbers b" " yes Error, All the numbers are True.

str.isidentifier()

Check whether the string starts with a letter .

'asdfghjkhl'.isidentifier()
Out[33]: True '1asdfghjkhl'.isidentifier()
Out[34]: False

str.islower()

If all the characters in the string are lowercase , And at least one character , Then return to True, Otherwise return to False.

'asdfghjkhl'.islower()
Out[37]: True 'asdfghjkHl'.islower()
Out[38]: False

str.isprintable()

Judge whether it's all visible / Printable characters

'asdf\nghjkHl'.isprintable()
Out[42]: False 'asdfghjkHl'.isprintable()
Out[43]: True

str.isspace()

Determine whether it is a space character ( Notice it's not empty )

''.isspace()
Out[44]: False ' '.isspace()
Out[45]: True 'ss'.isspace()
Out[46]: False

str.istitle()

It literally means : Determine whether a string can be used as a title

'Wo Shi Hao Ren 1'.istitle()
Out[50]: True 'Wo Shi Hao Ren The party '.istitle()
Out[51]: True 'Wo Shi Hao ren'.istitle()
Out[52]: False 'Wo Shi Hao Ren'.istitle()
Out[53]: True

str.title()

Change the string to the title format .

'wo shi hao ren'.title()
Out[140]: 'Wo Shi Hao Ren'

str.isupper()

And str.islower() Corresponding , If all the characters in the string are uppercase , And at least one character , Then return to True, Otherwise return to False.

str.join(string)

With str As a separator , take string All the elements are combined into a new string . if string It's empty , be TypeError.

''.join('asdfghjkl')
Out[55]: 'a111s111d111f111g111h111j111k111l' ''.join()
Traceback (most recent call last): File "<ipython-input-56-5fa735339586>", line 1, in <module>
''.join() TypeError: join() takes exactly one argument (0 given)

str.ljust(width,fillchar)

Get a left alignment of the original string , And use fiichar A new string filled to a specified length . If the specified length is less than the length of the original string, the original string is returned . And format The filling usage of is similar .

width-- Specify the length

fillchar-- Fill string , The default space character .

''.ljust(50)
Out[57]: '111 ' ''.ljust(50,'*')
Out[58]: '111***********************************************'
'{0:*<50}'.format('')
Out[62]: '111***********************************************'

str.rjust(width,fillchar)

Get an original string right aligned , And use fiichar A new string filled to a specified length . If the specified length is less than the length of the original string, the original string is returned . And format The filling usage of is similar .( Usage and ljust Agreement )

str.lower()

Convert all letters to lowercase , And str.upper() relative , And str.casefold() difference .

str.upper()

Turn all letters into capitals .

str.lstrip(chars)

Delete str All on the left appear in chars Substring ,chars When empty, the default space character .

' Wo Shi Hao ren '.lstrip()
Out[67]: 'Wo Shi Hao ren ' 'Wo Shi Hao ren'.lstrip('fdsfsfW')
Out[68]: 'o Shi Hao ren' 'Wo Shi Hao ren'.lstrip('fdsfsfw')
Out[69]: 'Wo Shi Hao ren'

str.rstrip(chars)

And str.lstrip(chars) Corresponding and consistent , Delete str All on the right appear in chars Substring ,chars When empty, the default space character .

str.strip(chars)

And str.lstrip(chars) and str.rstrip(chars) Use consistent , This is to delete all that appear on both sides of chars Substring ,chars When empty, the default space character .

'asdas'.strip('as')
Out[124]: 'd'

str.maketrans(intab,outtab)

Get one for str.translate() Mapping , It's actually a dictionary .

intab-- It's the original character

outtab-- Translated characters , Length vs in equal

intab = "abcde"
outtab = ""
name = "asdwgwegb"
x = ''.maketrans(intab, outtab)
name.translate(x) Out[103]: '1s4wgw5g2' ord('a') #a Of Unicode code
Out[104]: 97 x
Out[105]: {97: 49, 98: 50, 99: 51, 100: 52, 101: 53}

x Namely maketrans Get the dictionary , The mapping in the dictionary is character corresponding Unicode code .

str.translate()

according to str.maketrans Get the dictionary translation str

str.partition(char)    str.split(char,count)

The function is string segmentation

str.partition(char) According to the string char Division str Get one 3 Element tuples ( Recognize only the first occurrence of a string ).char Can't be empty

'asdsawoainiasdaswoainid'.partition('woaini')
Out[111]: ('asdsa', 'woaini', 'asdaswoainid') 'asdsawoainiasdaswoainid'.partition('woainid')
Out[112]: ('asdsawoainiasdas', 'woainid', '')

 str.split(char,count)   According to the string char Division str Get a list ( Identify all the char, also char Not included in the list ),char The default is the space character .

char-- Substring

count-- Number of cuts , Default all .

'asdsawoainiasdaswoainid'.split('woaini')
Out[113]: ['asdsa', 'asdas', 'd'] 'asdsawoainiasdaswoainid'.split()
Out[114]: ['asdsawoainiasdaswoainid'] 'asdsawoainiasdaswo ainid'.split()
Out[115]: ['asdsawoainiasdaswo', 'ainid']

str.rpartition(char)

Usage and str.partition(char) Agreement ,str.rpartition(char) According to the string char Division str Get one 3 Element tuples ( Only recognize The last time The string that appears ).char Can't be empty

str.rsplit(char,count)

And str.split Use consistent , however str.rsplit It's working from the back to the front ,str.split It's work after check-in .

'basdasa'.rsplit('as',1)
Out[131]: ['basd', 'a'] 'basdasa'.split('as',1)
Out[132]: ['b', 'dasa']

str.splitlines(keepends)

str.splitlines(keepends) Follow the line ('\r', '\r\n', \n') Separate , Get the list of elements in each row , If keepends by False, Does not contain line breaks , If True, Keep the newline . The default is False.

'asdsa\r\nwo\rainia\r\nsdas\nw\roainid'.splitlines()
Out[116]: ['asdsa', 'wo', 'ainia', 'sdas', 'w', 'oainid'] 'asdsa\r\nwo\rainia\r\nsdas\nw\roainid'.splitlines(False)
Out[117]: ['asdsa', 'wo', 'ainia', 'sdas', 'w', 'oainid'] 'asdsa\r\nwo\rainia\r\nsdas\nw\roainid'.splitlines(True)
Out[118]: ['asdsa\r\n', 'wo\r', 'ainia\r\n', 'sdas\n', 'w\r', 'oainid']

str.replace(old,new,count)

Put... In the string old( Old string ) Replace with new( New string ), Replace no more than count  Time ,count If it is empty, there is no limit to the number of times .

'asdas'.replace('as','sa',1)
Out[121]: 'sadas' 'asdas'.replace('as','sa')
Out[122]: 'sadsa'

str.startswith(start,end)

startswith() Method to check whether a string starts with a specified string , If it's a return True, Otherwise return to False.start,end Range not specified , Default 0,len(str)-1

'basdasa'.startswith('ba')
Out[135]: True 'basdasa'.startswith('ba',1,5)
Out[136]: False

str.swapcase()

Capitalize to lowercase , Lowercase to uppercase

'basdasaDASDA'.swapcase()
Out[138]: 'BASDASAdasda'

str.zfill(width)

width-- Specify the length

In string str Fill in the string before ‘0’, Make the length the specified length width.

'asdas'.zfill(10)
Out[141]: '00000asdas'

Reference resources :https://docs.python.org/3/library/stdtypes.html#string-methods

python More articles on string built-in methods

  1. 7.python character string - Built in method analysis

    The first one is right python The string built-in methods in are listed and briefly explained , But there are too many of them , It's too inefficient to recite one by one , Let me summarize these methods according to their functions : 1. Letters are case related ( Chinese is invalid ) 1.1 S.upper() -& ...

  2. 6.python character string - Built in method enumeration

    The so-called built-in method , Any string can be used , This method is in the class that creates the string , Here's the summary : First , We're going to learn a built-in function to get help  help( object ) , An object can be one that we create , It can also be the class that creates the object , ...

  3. python character string - Built in method enumeration

    The so-called built-in method , Any string can be used , This method is in the class that creates the string , Here's the summary : First , We're going to learn a built-in function to get help  help( object ) , An object can be one that we create , It can also be the class that creates the object , ...

  4. python character string - Built in method usage analysis

    1. Letters are case related ( Chinese is invalid ) 1.1 S.upper() -> string Returns a copy of all uppercase letters

  5. python Examples of string built-in methods

    One . String method summary : 1. lookup : find(rfind).index(rindex).count 2. Transformation : capitalize.expandtabs.swapcase.title.lower.up ...

  6. Python The use of string built-in methods and age game in-depth exploration

    Catalog Homework == The program code runs from top to bottom , It is suggested that the following tasks be completed from top to bottom == Homework Use code to implement the following business logic : Write code , There are the following variables name = " aleX", Please implement each function as required : move ...

  7. Python String built-in method notes

    One . toggle case ① capitalize() capitalize() # The initial of a string is uppercase >>> str0 = 'hello World' >>> str0.c ...

  8. python Data type built-in methods Strings and lists

    1. character string Built in method operation # a = 'qqssf'#1. print(a[-1:]) # Take... By index , Forward from 0 Start , Reverse from -1 Start # print(len(a)) # Take the length # a = 'qqssf'# 2. ...

  9. python Dictionary built in method get application

    python Dictionary built in method get application , If we need to get dictionary values , We can do it two ways , One is through dict['key'], The other is dict.get() Method . What I want to share with you today is the dictionary get() Method . this ...

Random recommendation

  1. On the desktop program and Metro/Modern/Windows store app Interaction ( Open to each other , Configure read )

    This title is really good. I think it hurts .. I don't know which one to call when Microsoft changed its name .. Here, record your desktop program and windows store app The process of interaction . For some reason , The security sandbox of Microsoft's store apps leads to a lot of things ...

  2. sql server Implementation plan (execution plan) Introduce

    The outline : Objective to introduce sql server General use of execution plan in , When there is a query performance bottleneck , It can be useful , And with more detailed learning documents and plans , Readers can follow my plan , So as to achieve a more systematic study of the implementation plan . What is? ...

  3. AJAX File upload practice and analysis , belt HTML5 Upload files API.

    about HTML5 Has supported AJAX The file was uploaded , But if you need to be compatible, you still need to use a little technique ,HTML5 And so on, introduction , Let's take a look at how we used to write . There may be some on the Internet called AJAX File upload plugin , But in AJAX2.0 It was impossible before ...

  4. combobox You can actively prompt the component to add the function of clearing unselected items

    The title is very tongue twister , But this is also the result of thinking for a long time , I'm sorry for the PE teacher . What the title wants to express is : I talked about it before combobox Implement your own active prompt component . It's only stipulated that the component can't be saved now data Data that does not exist in . The original idea was to go through ...

  5. Android UDP signal communication 2

    The server realizes one sending and one receiving Server code : import java.net.*; import java.io.*; public class udpRecv2 { /* * establish UDP The receiving end of the transmission * 1. build ...

  6. Study python One month inventory

    1, I saw 30 Multiple videos , It's some basic operations . A rough understanding of the grammar , function , loop , Regular expression , Type all the video content into the text : 2, I saw 100 Page book , The exercises are not very good , It's going very slowly . The fifth chapter 10 I didn't do any questions later : 3, see C++ The book of , somewhat ...

  7. jQuery - Detect value change on hidden input field

    You can simply use the below function, You can also change the type element. $("input[type=hidd ...

  8. 【 Reprint 】SeleniumIDE introduction

    http://www.open-open.com/lib/view/open1452488109558.html

  9. hermes kafka turn http rest api Of broker Tools

    hermes And nakadi It's a similar tool , But design models are very different ,hermes It uses webhook The pattern of (push) nakadi It uses pull(event stream), Each has its own solution ...

  10. Socket Model ( Two ): Completion port (IOCP)

    Why use Socket Model , Instead of using Socket? The reason is that recv() The method is plug-in , When multiple clients connect to the server , One of them socket Of recv Invocation time , There will be a blockage , Make other links unable to continue . In this way, we ...