current position:Home>Python Xiaobai foundation -- string

Python Xiaobai foundation -- string

2022-07-25 11:19:45CoderEnd

#  Basic concepts of string 
'''  Variables as defined below a, What is stored is the value of the number type  a = 100  Variables as defined below b, What is stored is a string type value  b = "hello itcast.cn"  perhaps  b = 'hello itcast.cn'  A small summary :  Data in double or single quotes , It's just a string  '''

#  String input and output  
#  It is basically the same as ordinary input and output 
#demo1  Output 

name = 'xiaoming'
position = ' lecturer '
address = ' The Beijing municipal '

print('--------------------------------------------------')
print(" full name :%s"%name)
print(" Position :%s"%position)
print(" The company address :%s"%address)
print('--------------------------------------------------')

#demo2  Input 

userName = input(' Please enter a user name :')
print(" The user is called :%s"%userName)

password = input(' Please input a password :')
print(" The password for :%s"%password)


#  String subscript slice 

#  Subscript 
'''  In a string " Subscript " Use   List and tuple support subscript index , String is actually an array of characters , So subscript index is also supported .  amount to C An array of characters in a language   The array is from the subscript 0 At the beginning  int array[]="helloVscode" array[0]='h' array[1]='e' array[2]='l' array[3]='l' array[4]='o' '''

Str = 'helloVscode'
print(Str[0])
print(Str[10])
#  Format output 
print("Str[1]=%s"%Str[1])
print("Str[5]=%s"%Str[5])
print("Str[9]=%s"%Str[9])
'''  result  h e Str[1]=e Str[5]=V Str[9]=d '''

'''  Slicing refers to the operation of intercepting part of the operation object . character string 、 list 、 Tuples all support slicing .  The syntax of slicing :[ start : end : step ]  Be careful : The selected interval is left closed and right open , From " start " Bit start , To " end " The last one of the first ( Does not include the end bit itself ) '''

# demo
#  The syntax of slicing :[ start : end : step ]
# str = [N0:Nn:Step]  Before closed after opening 

String = 'Vscode_Python'  
#  From left to right  0--》》
#  From right to left  《《--1
#  step  Step  The default is 1( You can omit it ) 
# [::1]  Default   from 0 To the last 
#  step  Step>0  Sequence direction  Step<0  Reverse direction 
print(String[0:6:1]) 

print(String[7:13:1]) 

print(String[::-1])
print(String[1:-1])
# a[5:1:-2]
print(String[5:0:-2])


'''  result  Vscode Python nohtyP_edocsV scode_Pytho eos '''



#  Given a string aStr,  Please reverse the string 

str1="aStr"
reverse = str1[::-1]  
print(reverse)

#  String common operations 

#  character string   Method 
''' capitalize()  Convert the first character to uppercase . casefold()  Convert string to lowercase . center()  Returns a centered string . count()  Returns the number of occurrences of the specified value in the string . encode()  Returns the encoded version of the string . endswith()  If the string ends with the specified value , Then return to  true. expandtabs()  Set the value of the string  tab  Size . find()  Searches the string for the specified value and returns where it was found . format()  The specified value in the format string . format_map()  The specified value in the format string . index()  Searches the string for the specified value and returns where it was found . isalnum()  If all characters in the string are alphanumeric , Then return to  True. isalpha()  If all the characters in the string are in the alphabet , Then return to  True. isdecimal()  If all characters in the string are decimal , Then return to  True. isdigit()  If all the characters in the string are numbers , Then return to  True. isidentifier()  If the string is an identifier , Then return to  True. islower()  If all the characters in the string are lowercase , Then return to  True. isnumeric()  If all characters in the string are numbers , Then return to  True. isprintable()  If all characters in the string are printable , Then return to  True. isspace()  If all characters in the string are white space characters , Then return to  True. istitle()  If the string follows the title rule , Then return to  True. isupper()  If all the characters in the string are uppercase , Then return to  True. join()  Connect the elements of the iteratable object to the end of the string . ljust()  Returns the left aligned version of a string . lower()  Convert string to lowercase . lstrip()  Returns the left trimmed version of the string . maketrans()  Return the conversion table used in the conversion . partition()  Return a tuple , The string is divided into three parts . replace()  Return string , Where the specified value is replaced by the specified value . rfind()  Search the string for the specified value , And return to the last place it was found . rindex()  Search the string for the specified value , And return to the last place it was found . rjust()  Returns the right justified version of a string . rpartition()  Return a tuple , The string is divided into three parts . rsplit()  Splits the string at the specified delimiter , And return to the list . rstrip()  Returns the right trimmed version of the string . split()  Splits the string at the specified delimiter , And return to the list . splitlines()  Splits the string at the line break and returns a list . startswith()  If the string starting with the specified value , Then return to  true. strip()  Returns the clipped version of the string . swapcase()  Toggle case , Lowercase becomes uppercase , vice versa . title()  Convert the first character of each word to uppercase . translate()  Returns the converted string . upper()  Convert strings to uppercase . zfill()  Fills the beginning of the string with the specified number of  0  value . '''

# find  Determine whether a string appears in other strings 
MyStr = 'HelloPython VscodePython Python Anconda Pythondeeplearning AI OpenCV PythonCSS'
mystr = MyStr.find("Vscode")
mystr2 = MyStr.find("Python")
print(mystr)
print(mystr2)
''' MyStr.find() find(sub, start=0, end=-1) str.find(str, beg=0, end=len(string)) str --  Specifies the string to retrieve  beg --  Start index , The default is 0. end --  End index , The default is the length of the string .  If it contains a substring, it returns the starting index value , Otherwise return to -1. '''

# index
#  And  find() The method is the same , Just if str be not in  mystr An exception will be reported in 
mystr = MyStr.index("Vscode")
print(mystr)

''' index() Method syntax : index(sub, start=0, end=-1) S.index(sub[, start[, end]]) -> int str.index(str, beg=0, end=len(string))  Parameters  str --  Specifies the string to retrieve  beg --  Start index , The default is 0. end --  End index , The default is the length of the string .  Return value   If it contains a substring, it returns the starting index value , Otherwise, throw an exception . '''

'''  result : Traceback (most recent call last): File "e:/Desktop/Code/python/Basic/str2.py", line 26, in <module> mystr = MyStr.index("Vscde") ValueError: substring not found '''


''' count  return  str stay start and end Between   stay  mystr The number of times it's inside  ount() Method syntax : str.count(sub, start= 0,end=len(string))  Parameters  sub --  Search for substrings  start --  Where the string starts searching . The default is the first character , The first character index value is 0. end --  Where to end the search in the string . The index of the first character in the character is  0. Default to the last position of the string .  Return value   This method returns the number of times the substring appears in the string . '''
mycount = MyStr.count(' ') #  Number of spaces 
print(mycount) 

''' replace() Method syntax : str.replace(old, new[, max])  Parameters  old --  Substring to be replaced . new --  New string , Used for replacement old Substring . max --  Optional string ,  Replace no more than  max  Time   Return value   Returns... In the string  old( Old string )  Replace with  new( New string ) New string generated after , If you specify the third parameter max, The substitution does not exceed  max  Time . '''
mystr3  = 'HelloPython VscodePython Python Anconda Pythondeeplearning AI OpenCV PythonDjanjo Pythonrqequest'
print(MyStr)
print(mystr3)

myreplace = MyStr.replace('Python','pythontest',)
print(myreplace)
myreplace1 = mystr3.replace('Python','LearningPython',3) 

# old  The string to be replaced 
# new  New string , The string you need now 
# max: Maximum times  The maximum number of replacements should not exceed  Max
print(myreplace1)

'''  result  Hellopythontest Vscodepythontest pythontest Anconda pythontestdeeplearning AI OpenCV pythontestCSS HelloLearningPython VscodeLearningPython LearningPython Anconda Pythondeeplearning AI OpenCV PythonDjanjo Pythonrqequest '''


''' split  With  str  Slice for separator  mystr, If  maxsplit There is a specified value , Only separate  maxsplit  Substring   grammar  split()  Method syntax : str.split(str="", num=string.count(str)).  Parameters  str --  Separator , The default is all empty characters , Including Spaces 、 Line break (\n)、 tabs (\t) etc. . num --  Number of divisions . The default is  -1,  To separate all .  Return value   Returns a list of split strings  '''
mystr4  = 'HelloPython VscodePython Python Anconda deeplearningAI OpenCV PythonDjanjoPythonrqequest'
mysplit = mystr4.split(' ') #  The default is  -1,  To separate all .
mysplit2 =mystr4.split(' ',3) #  Number of splits 
print(mysplit)
print(mysplit2)

'''  result  ['HelloPython', 'VscodePython', 'Python', 'Anconda', 'deeplearningAI', 'OpenCV', 'PythonDjanjoPythonrqequest'] ['HelloPython', 'VscodePython', 'Python', 'Anconda deeplearningAI OpenCV PythonDjanjoPythonrqequest'] '''


 
#  The second parameter is  1, Returns a list of two parameters 
#  The following examples are as follows  #  The sign is a separator , Specify the second parameter as  1, Returns a list of two parameters 
txt = "Google#Runoob#Taobao#Facebook"
x = txt.split("#", 1)
y = txt.split('#',)

print(x)
print(y)

'''  result : ['Google', 'Runoob#Taobao#Facebook'] ['Google', 'Runoob', 'Taobao', 'Facebook'] '''

''' capitalize  Capitalize the first character of a string  Python capitalize() Change the first letter of the string to uppercase , Other letters become lowercase . about  8  Bit byte encoding needs to be based on the local environment .  grammar  capitalize() Method syntax : str.capitalize()  Return value   This method returns an uppercase string . '''

mystr5 = 'learnPython'
mycapitalize = mystr5.capitalize()
print(mycapitalize)

''' title  Capitalize each word in the string  '''
# demo 

mystr6 = 'helloPython vscodePython python anconda deeplearningAI openCV pythonDjango pythonrqequest'
mytitle = mystr6.title()
print(mystr6)
print(mytitle)

'''  result : helloPython vscodePython python anconda deeplearningAI openCV pythonDjango pythonrqequest Hellopython Vscodepython Python Anconda Deeplearningai Opencv Pythondjango Pythonrqequest '''

'''  Definition and Usage   If the string starts with the specified value , be  startswith()  Method returns  True, Otherwise return to  False.  grammar  string.startswith(value, start, end)  Parameters  value  It's necessary . Check whether the string starts with its value . start  Optional . Integers , Specify where to start searching . end  Optional . Integers , Specify where to end the search . '''

txt = "Hello, welcome to my world."

x = txt.startswith("wel", 7, 20)
y = txt.startswith("ssr")
print(x)
print(y)
'''  result : True False '''

''' endswith  If the string ends with the specified value , be  endswith()  Method returns  True, Otherwise return to  False.  grammar  string.endswith(value, start, end)  Parameters  value  It's necessary . Check whether the string ends with the value . start  Optional . Integers . Specify where to start searching . end  Optional . Integers . Specify where to end the search  '''

txt = "Hello, welcome to my world."
txt1 = '2020-07-07 Learnpython'

x = txt.endswith("my world.", 5, 11)
y =txt1.endswith('python')
print(x) # False 
print(y) # True


''' Python lower()  Method to convert all uppercase characters in a string to lowercase  str.lower()  Return value   Returns the string generated after converting all uppercase characters in the string to lowercase  '''

str7 = "THIS IS STRING EXAMPLE....WOW!!!";

print(str7.lower())

'''  result : this is string example....wow!!! '''

''' Python upper()  Method to convert lowercase letters in a string to uppercase letters .  Return value   Returns a string that converts lowercase letters to uppercase letters . '''

str8 = "this is string example....wow!!!"

print(str8.upper())

'''  result : THIS IS STRING EXAMPLE....WOW!!! '''

''' Python ljust()  Method returns a left aligned original string , And fill the new string with spaces to the specified length . If the specified length is less than the length of the original string, return the original string . Python rjust()  Returns an original string to the right , And fill it with Spaces to length  width  New string of . Returns the original string if the specified length is less than the length of the string . str.ljust(width[, fillchar]) str.rjust(width[, fillchar])  Parameters  width --  Specify string length . fillchar --  Fill character , Default is space .  Return value  ljust:  Returns an original string left aligned , And fill the new string with spaces to the specified length . If the specified length is less than the length of the original string, return the original string . rjust:  Returns an original string to the right , And fill it with Spaces to length  width  New string of . Returns the original string if the specified length is less than the length of the string  '''

str9 = "this is string example....wow!!!"

print(str9.ljust(50,'0'))
print(str9.rjust(50,'0'))

print(str9.ljust(50))
print(str9.rjust(50))

# l  Left 
# r  Right 
'''  result : this is string example....wow!!!000000000000000000 000000000000000000this is string example....wow!!! this is string example....wow!!! this is string example....wow!!! '''

''' lstrip  Delete  mystr  The white space on the left  Python lstrip()  Method is used to cut the space to the left of the string or the specified character . str.lstrip([chars]) chars -- Specifies the character to be intercepted .  Return value   Returns a new string generated after cutting off the space on the left of the string or the specified character . '''
str10 = " this is string example....wow!!! "
print(str10)
print(str10.lstrip())
str11 = "88888888this is string example....wow!!!8888888"
print(str11)
print(str11.lstrip('8'))

''' this is string example....wow!!! this is string example....wow!!! 88888888this is string example....wow!!!8888888 this is string example....wow!!!8888888 '''

''' Python rstrip()  Delete  string  The specified character at the end of the string ( Default is space ) str.rstrip([chars]) chars --  Specify the characters to delete ( Default is space )  Go back to delete  string  A new string generated after the specified character at the end of the string . '''

str12 = " this is string example....wow!!! "
print(str12)
print(str12.rstrip()) 
str13 = "88888888this is string example....wow!!!8888888"
print(str13)
print(str13.rstrip('8'))

'''  result : this is string example....wow!!! this is string example....wow!!! 88888888this is string example....wow!!!8888888 88888888this is string example....wow!!! '''


###  String method 
#  character string   Method 
1. capitalize() Convert the first character of the string to uppercase 
2. center(width,fillchar) Returns a specified width width Centered string ,fillchar Characters to be filled , Default is space .
3. count(str,beg=0,end=len(string) return  str stay string The number of times it's inside , If beg perhaps end If specified, return to the specified range  str Number of occurrences 
4. bytes.decode(encoding="utf-8",errors="strict")Python3 There is no  decode Method , But I 4 We can use bytes Object's decode() Method to decode the given bytes object , This bytes Objects can be str.encode() To code the return .
5. encode(encoding='UTF-8,errors='strict) With encoding The specified encoding format encodes the string , If there is an error, one will be reported by default ValueError It's abnormal , Unless  errors  Specifies the ignore' perhaps ’replace'
6. endswith(suffix,beg=0,end=len(string)) Check whether the string uses obj end , If beg  perhaps end Specify to check whether the specified range is in the range of obj end , If it is , return True, Otherwise return to False.
7. expandtabsttabsize=8) Put the string  string Medium tab Turn the symbol into a space ,tab The default number of spaces for symbols is 8.
8. rstrip()  Remove the space at the end of the string string 
9. find(str, beg=0, end=len(string))  testing  str  Whether to include in the string , If you specify a range  beg  and  end, Then check whether it is included in the specified range , If it contains the index value that returns the start , Otherwise return to -1
10. index(str, beg=0, end=len(string))  Follow find() The method is the same , Just if str Not in the string will report an exception .
11. isalnum()  Returns if the string has at least one character and all characters are letters or numbers   return  True, Otherwise return to False
12. isalpha()  Returns if the string has at least one character and all characters are letters  True,  Otherwise return to  False
13. isdigit()  Returns if the string contains only numbers  True  Otherwise return to  False
14. islower()  If the string contains at least one case sensitive character , And all of this ( case-sensitive ) All characters are lowercase , Then return to  True, Otherwise return to  False
15. isnumeric()  If the string contains only numeric characters , Then return to  True, Otherwise return to  False
16. isspace()  If the string contains only white space , Then return to  True, Otherwise return to  False
17. istitle()  If the string is titled ( see  title()) Then return to  True, Otherwise return to  False
18. isupper()  If the string contains at least one case sensitive character , And all of this ( case-sensitive ) All characters are uppercase , Then return to  True, Otherwise return to  False
19. join(seq)  Use the specified string as the separator , take  seq  All the elements in ( String representation of ) Merge into a new string 
20. len(string)  Return string length 
21. [ljust(width, fillchar])  Returns an original string left aligned , And use  fillchar  Fill to length  width  New string of ,fillchar  Default is space 
22. lower()  Convert all uppercase characters in the string to lowercase 
23. lstrip()  Truncates the space to the left of the string or specifies the character 
24. maketrans()  Create a conversion table for character mapping , For the simplest call to accept two parameters , The first parameter is the string , Indicates the character to be converted , The second parameter is also the target of string representation transformation 
25. max(str)  Return string  str  The largest letter in 
26. min(str)  Return string  str  The smallest letter in 
27. [replace(old, new , max])  hold   In the string  str1  Replace with  str2, If  max  Appoint , The substitution does not exceed  max  Time 
28. rfind(str, beg=0,end=len(string))  Be similar to  find() function , Just search from the right 
30. rindex( str, beg=0, end=len(string))  Be similar to  index(), It's just from the right 
31. [rjust(width,, fillchar])  Returns an original string to the right , And use fillchar( Default space ) Fill to length width  New string of 











copyright notice
author[CoderEnd],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/206/202207251018188289.html

Random recommended