These are the 5 days of my participation in the November Gwen Challenge. Check out the details of the event: the last Gwen Challenge 2021.

string

Strings are one of the most common data types in Python, using single or double quotes to create strings, and triple quotes to create multi-line strings.

Strings are immutable sequence data types that cannot be modified directly, just like numeric types. So when we want to retrieve a letter from “Hello world”, we need to retrieve it from the index (which starts at 0 by default) :

>>> s1 = "hello world"          
>>> s1[1]               
'e'
>>> s1[10]
'd'
>>> s1[-1]
'd'
>>> s1[11]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
Copy the code

⚠️ Note: Strings are immutable data types.

String slice (slice)

Type help(slice) to view the slice description document:

slice(start, stop[, step])
Copy the code
  • startStarting position, the default index starts at 0
  • stopEnd position, default last element
  • stepStep size, default is 1
  1. from"hello world"Take out theworldValue:
> > > s3 = "hello world" > > > s3 [should] # note that left closed right away 'worl' > > > s3 [they] 'world' > > > s3 [6:] # don't write the default to the last 'world'Copy the code
  1. Reverse output:
>>> s3[::-1]
'dlrow olleh'
Copy the code
  1. Convert a string to an integer:
>>> int('1')
1
Copy the code
  1. Convert an integer type to a string:
>>> str(1)
'1'
Copy the code
  1. Concatenation string:
print('1'+'2')  # 12
Copy the code
  1. Format string:

    %s %d %f:

    str.format():

    shorthandstr.format:
Print ('%s age %d'%(name,age))Copy the code
Name = 'cat' age = 18 print (' {} {} age. The format (name, 18)) print (' {0} {1} age. The format (18, name))Copy the code
Name = 'cat' age = 18 print(f'{name} = {age}')Copy the code

Common methods for strings

  1.  S.find(sub)Returns the smallest index of this element:
> > > s4 = 'hello python' > > > s4. Find (' e ') 1 > > > s4. Find (' o ') # when elements have multiple return index of minimum 4 > > > s4. Find (' c ') # can't find it is - 1-1Copy the code
  1.  S.index(sub)Returns the smallest index of the elements.find()It does the same thing, but the only difference is that when the element doesn’t exist,s.index()The method returns an error. So it’s recommended to uses.find().
  2.  S.replace(old, new[, count])Replacement:
>>> s5 = "hello python" >>> s5.replace('l','a') # replace 'l' with 'a', all replace 'heaao python' >>> s5 'hello python' # >>> s5.replace('l','a',1) # replace('l','a',1) #Copy the code
  1.  S.split(sep=None)In order tosepTo split the string and return the list.sepThe default isNone, the default partition is space:
>>> s6 = 'hello everyboby ye! ' >>> s6.split(' ') ['hello', 'everyboby', 'ye!']Copy the code
  1.  S.startswith(prefix[, start[, end]])Checks if the string starts with a prefix, returnsboolValue:
>>> s7 = "hello world"
>>> s7.startswith("he")
True
Copy the code
  1.  S.endswith(suffix[, start[, end]])Checks if the string ends with a suffix, returnsboolValue:
>>> s7
'hello world'
>>> s7.endswith('ld')
True
Copy the code
  1.  S.lower()Convert all strings to lowercase.
  2.  S.upper()Uppercase all strings.
  3.  S.strip([chars])Defaults to removing Spaces around strings:
>>> s8 = '  hello world   '
>>> s8.strip()
'hello world'
Copy the code
  1.  S.isalpha()Checks if the string is all letters, returnsboolValue.
  2.  S.isdigit()Checks if the string is all numbers, returnsboolValue.
  3.  S.isalnum()Checks whether the string is all numbers or letters. No special characters existboolValue.
  4.  S.join(iterable)Generates a new string with the specified concatenation of the elements in the sequence.