We learned before about an immutable sequence called tuples , Today we're talking about strings , It's also an immutable sequence .

List of articles

    • 1) Query operation
    • 2) Common operation of string
    • a) toggle case
    • b) String content alignment operation
    • c) String splitting
    • d) String judgment method
    • e) Other operations of strings
    • f) String comparison
    • g) Slice of string
    • h) Formatted string
    • 1) Definition of string
    • 1. String creation
    • 2. Common operation of string
    • summary


1. String creation

A concept : The resident mechanism of string
So what is the string resident mechanism ?
intend : Methods that keep only one copy of the same and immutable string , Different values are stored in the resident pool of strings ,python Only one copy of the same string is retained by the resident mechanism of , When creating the same string later , It won't open up new space , Instead, the address of the string is reassigned to the new variable .

1) Definition of string

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6sa='itlaoxin'b="itlaoxin"c='''itlaoxiin'''print(a,b,c,id(a),id(b),id(c))

Output results
 Insert picture description here

You can see ID It's all the same .

There is only one copy in memory

A few notes :
In interactive mode , Can implement the resident mechanism :

  • The length of the string is 0 perhaps 1 when
  • A string that matches the identifier
  • Strings only reside at compile time , Not the runtime
  • 【-5,256】 An integer number between
  •  Insert picture description here

2. Common operation of string

About string operations , We can think of a string as a list of characters :

1) Query operation

  • index() Find string substr First occurrence , If the substring you are looking for does not exist , Throw an exception
  • rindex() Find string substr The last problem , If it doesn't exist , Abnormal Report
  • find() Find substring substr First occurrence , There is no return -1
  • rfind Find substring substr The last location , If there is no return -1
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss='hello,world'print(s.index('l')) #2print(s.find('l')) #2print(s.rfind('l')) #9print(s.rindex('l')) #9

Here we suggest you use find, perhaps rfind, Because there's no exception

2) Common operation of string

a) toggle case

  • upper() Convert all characters in a string to uppercase letters ( A new string object is generated )
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello,ITlaoxin"a=s.upper()print(s)print(a)

  • lower() Convert all characters in a string to lowercase letters
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello,ITlaoxin"a=s.lower()print(s)print(a)

Output results :
hello,ITlaoxin
hello,itlaoxin

  • swapcase() Convert all uppercase letters in a string to lowercase letters , Convert all lowercase letters to uppercase letters
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello,ITlaoxin"a=s.swapcase()print(a,id(a))print(s,id(s))

  • capitalize() Convert the first character to uppercase , Convert the rest of the characters to lowercase
  • tilele( ) Convert the first character of each word to uppercase , Convert the remaining characters of each read word to lowercase
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello,ITlaoxin"a=s.title()print(a)

b) String content alignment operation

  • center() Align center
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello,ITlaoxin"print(s.center(20,'*'))

 Insert picture description here
altogether 14 Characters , Definition 20 Characters , Three on the left and three on the right

  • ljust() Align left
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello,ITlaoxin"print(s.ljust(20,"*"))

 Insert picture description here
If you don't write * , Default is space

  • rjust Right alignment
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello,ITlaoxin"print(s.rjust(20,"*"))

 Insert picture description here

  • zfill Right alignment
    This way it works 0 fill
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello,ITlaoxin"print(s.zfill(20))

 Insert picture description here

c) String splitting

  • split() Division , Start on the left , The default separator is space , After splitting, there's a list
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello,ITlaoxin"lst=s.split()print(lst)

Output results :

['hello,ITlaoxin']

We can specify the separator , use sep=‘|’ In the form of

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello|ITlaoxin|gaosh"lst=s.split(sep='|')print(lst)

Output results

['hello', 'ITlaoxin', 'gaosh']

If we use the default space in this place, what will be the result :

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello|ITlaoxin|gaosh"lst=s.split()print(lst)

result

['hello|ITlaoxin|gaosh']

You can see , Because there are no spaces in this string , So it's a list of elements .

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello|ITlaoxin|gaosh"lst=s.split(sep='|',maxsplit=1)print(lst)

result :

['hello', 'ITlaoxin|gaosh']

There's only one split here .

  • rsplit() Split from the right side of the character , The default split character is space , The return value is a list
    maxsplit You can specify the maximum number of splits

This and split We use it the same way , It's just rsplist It's split from the right ,splist Split from the left

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss="hello|ITlaoxin|gaosh"lst=s.split(sep='|',maxsplit=1)print(lst)lst1=s.rsplit(sep='|',maxsplit=1)print(lst1)

The result is shown in the figure :
 Insert picture description here

d) String judgment method

  • isidentifier() Determine whether the specified string is a legal identifier
  • isspace() Determines whether the specified string consists of all white space characters ( enter , Line break , Horizontal refers to the tab )
  • issalpha() Determines whether a string is made up entirely of letters
  • isdecimal( ) Determines whether the specified string is all decimal
  • isnumeric() Judge that the specified string is composed of all numbers
  • isalnum() Determine whether the specified string is composed of all letters and numbers
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss='hello,world,python'print('1',s.isidentifier())print('2','hello'.isidentifier())print('3','\t'.isidentifier())print('4','abc'.isspace())print('5','abc'.isalpha())print('6','1'.isspace())print('7','123'.isnumeric())print('8','abc123'.isalnum())print('9','123abc!'.isalnum())

e) Other operations of strings

  • String replacement replace()
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6ss='hello,world,python'print(s.replace('python','itlaoxin'))s1='hello,python,python ,python'print(s1.replace('python','itlaoxin',2))

result :

hello,world,itlaoxin
hello,itlaoxin,itlaoxin ,python

  • String merging join()
#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6slst=['hello','java','python']print('|'.join(lst))

result :hello|java|python

f) String comparison

Use the operator >,>= ,<,<= ,= ,!=

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6sprint('1','itlaoxin'>'laoxin')print('2','itlaoxin'>'itlaox')

 result :
1 False
2 True

If the first letter is different , Just compare the original value ord()

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6sprint('1','itlaoxin'>'laoxin')print('2','itlaoxin'>'itlaox')print('3','python'>'java')##  amount to print(ord('p'),ord('j'))

 Insert picture description here

The third is equivalent to 112 And 106 Compare

g) Slice of string

Strings are immutable types , Do not have the operation of adding, deleting, modifying and checking , Slicing creates new objects

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6sa='hello,world,itlaoxin'print(a[:5])

Output results :
hello

Don't write the starting position , It will be from index0 Start cutting

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6sa='hello,world,itlaoxin'print(a[6:]) #world,itlaoxin

No end position specified , It will cut to the end

step Is the specified step size

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6sa='hello,world,itlaoxin'print(a[1:8:2]) #el,o

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6sa='hello,world,itlaoxin'print(a[1:8:2])print(a[::2]) #hlowrdiloi

h) Formatted string

Why format strings ?
The splicing of strings produces new Id, It's a waste of space , At this time, you need to use string formatting .

Two ways to format strings :
% Do a placeholder

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6s# The first way %name=' Internet veteran Xin 'age=40
print(' My name is %s, This year, %d Year old '%(name,age))

{} Do a placeholder

To use format() Method

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6s# The first way %name=' Internet veteran Xin 'age='40'print(' My name is {0}, This year, {1} Year old '.format(name,age))

In addition, it can also express intensive reading and width :

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6sprint('%d'% 99)print('%10d'% 99)

there 10 It's the width

precision :
Retain 3 Decimal place

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6sprint('%.3f' % 3.11516)

A mixture of :

#  author : Internet veteran Xin #  Development time :2021/4/4/0004 6sprint('%10.3f' % 3.11516)

%10.3f
The total width is 10, The decimal point is reserved 3 position

summary

Up to now, the basic operation of all data types has been introduced , These should be the basis , Next we're going to the function section .

I'm Xin, an Internet veteran , Working in the technology industry has 12 Years. , The education industry 5 year , I'm an old man . Start sharing what you've learned this year , I hope I can help you , If it works for you , You can like the collection .
Every time you forward , Collection , Are the greatest encouragement to the author .