Basic operation of string in Python

1, String

A string can be understood as an ordinary piece of text. In python, quotation marks are used to represent a string. The effects of different quotation marks will be different.

str = 'Hello World'  # A pair of single quotation marks
str = "Hello World"  # A pair of double quotation marks
str = 'Tom said:"I am Tom!"'  # A pair of single quotation marks
str = 'Tom said:"I\'m Tom!"'  # Escape character
str = """Tom said:"I'm Tom!"""  # Three double quotes
str = '''Tom said:"I'm Tom!'''  # Three single quotes
  • The data in double quotation marks or single quotation marks is a string
  • If you use a pair of quotation marks to define a string, you can use escape characters when there is a symbol conflict
  • A string defined with three single and double quotation marks can wrap any text

2, Escape character

Escape charactermeaning
\rMove the current position to the beginning of the line
\nLine feed
\tUsed to represent a tab
\\Represents a backslash character\
\'Used to display a single quotation mark
\''Used to display a double quotation mark

3, String index

In the computer, each string is stored in the corresponding position. To take out the corresponding character, we need to use the subscript method (subscript starts from 0)

a = 'abcdefg'
print(a[0])
print(a[1])
print(a[2])

result:

Note: the index subscript range of the string is 0 to (len-1) or (- len) to - 1

4, String traversal

The so-called traversal can be understood as accessing each data according to certain rules (generally, it is the subscript of the data). Not all data can be traversed. Strings are iteratable objects that can be traversed.

You can use the while and for statements to traverse the elements in the string.

  • while loop traversal
a = 'abcdefg'
i = 0
while i < len(a):
    print(a[i])
    i += 1
  • for loop traversal
a = 'abcdefg'
for i in a:
    print(i)

5, String slicing

Tiles: strings, lists
 Formats: string variables[start:end:step]---> start~end-1,default start 0, left closed right open;last step The parameter is step size, which is 1 by default,Taking a negative number means taking a negative number in the opposite direction
 Example:
a = 'hello world'
print(a[0:5]) ---> hello
print(a[-5:-1]) ---> worl 
print(a[-5:]) ---> world
print(a[1:-1]) ---> ello worl 
print(a[::2]) ---> hlowrd
print(a[::-1]) ---> dlrow olleh
print(a[::-2]) ---> drwolh

6, Common operations of string

The len function can get the length of the string

a = 'hello world'
print(len(a)) # ----> 11

  1. find

    Finds whether the specified content exists in the string. If it exists, it returns the start position index value of the content for the first time in the string. If it does not exist, it returns - 1

    Syntax format:

S.find(sub[, start[, end]]) -> int

Example:

‚Äč

a = 'Take advantage of the situation and start a new journey of socialist modernization in an all-round way. Long live the people's Republic of China! Long live socialism!'
print(a.find('socialist'))  # --->When 'socialism' first appeared, where was' society '
print(a.find('social phobia'))  # --->- 1 'social fear' does not appear in the string, return - 1
print(a.find('Sociology', 12))  # --->31 start from subscript 12 to find 'society', and the location of finding 'society' is
print(a.find('Sociology', 1, 6))  # --->- 1 search for 'society' from subscripts 1 to 6. If it is not found, return - 1
  1. rfind

It is similar to the find function, but it starts from the right.

  1. index

It is similar to the find function, but when the find method is not found, it returns - 1, and when the index is not found, it will report an error.

  1. rindex

It is the same as index(), but it starts from the right.

  1. startswith

Determines whether the string starts with the specified content. The result returns a Boolean value. Syntax format:

S.startswith(prefix[, start[, end]]) -> bool
  1. endswith

Similar to the startswitch function, it determines whether the string ends with the specified content. Also returns a Boolean value.

  1. isalpha

To determine whether the string is a pure letter, a Boolean value is also returned.

  1. isdigit

Judge whether the string is a pure number. As long as there are numbers other than 0-9, the result is False.

  1. isalnum

Judge whether the string is composed of numbers and letters. As long as there are non numbers and non letters, the result is False.

  1. isspace

Determines whether the string contains only spaces. If so, it returns True.

count

Calculate the number of occurrences of a character or string in a string. Syntax format:

S.count(sub[, start[, end]]) -> int

Example:

mystr = 'Take advantage of the situation and start a new journey of socialist modernization in an all-round way. Long live the people's Republic of China! Long live socialism!'
print(mystr.count('hooray'))  # 2. The word "long live" appears twice

replace

Replace the content specified in the string. If count is specified, the replacement will not exceed count

Example:

str = 'You say? rap I said No!'
new_str1 = str.replace('No', 'Yes')
new_str2 = str.replace('say', 'sing')
new_str3 = str.replace('say', 'sing', 1)
print(new_str1,new_str2,new_str3)

result:

  1. split

Slice with the specified string as the separator. If maxplit has the specified value, only maxplit + 1 substrings will be separated. The result returned is a list.

Example:

a = 'Take advantage of the situation and start a new journey of socialist modernization in an all-round way. Long live the people's Republic of China and socialism!'
result = a.split()  # There are no white space characters, so the string is not split
result1 = a.split('Sociology')  # Use 'social' as separator
result2 = a.split('Sociology', 1)  # With 'society' as the separator, it can be divided into 2 copies at most
print(result)
print(result1)
print(result2)

result:

2. rsplit

The usage is the same as split, but it is divided from right to left

  1. splitlines

Split by row, returns a list containing each row as an element

Example:

mystr = 'hello \nworld'
print(mystr.splitlines())

result:

4. partition

Split the string into three parts with the selected content. Example:

a = 'Take advantage of the situation and start a new journey of socialist modernization in an all-round way. Long live the people's Republic of China and socialism!'
print(a.partition('Sociology'))

result:

5. rpartition

Like partition, it just starts from the right

The function of changing case is only valid for English, mainly including: capitalize the first letter, capitalize the first letter of each word, title, all lowercase lower and all uppercase upper.

  1. ljust

Returns a string of the specified length and fills it with white space characters on the right, that is, left justified.

  1. rjust: right justified.
  2. center: center.
  3. lstrip: delete the white space character to the left of the string.
  4. rstrip: deletes the white space character to the right of the string
  5. strip: delete white space characters at both ends.

Example:

a = 'hello world'
str = a.ljust(15)
print(str)
print(len(str))
str1 = a.rjust(15)
print(str1)
str2 = a.center(15)
print(str2)

result:

Traverse the parameters, take out each item in the parameters, and then add the string to be spliced, and do not add after the last parameter.

Example:

str = 'a'
print(str.join('123'))
print(str.join(['keep','good','data']))

result:

Function: you can quickly convert a list or tuple into a string and divide it with specified characters

Example:

txt = '_'
print(txt.join(['a', 'b', 'c']))
print(txt.join(('a', 'b', 'c')))

result:

7, Supplementary notes

  1. The addition operator can be used between strings to splice two strings into one string. For example, the result of 'hello' + 'world' is' hello world '
  2. You can multiply between a string and a number, and the result is to repeat the specified string multiple times. For example, the result of 'hello'*2 is hello hello
  3. If the comparison operator is used to calculate between strings, the encoding corresponding to the character will be obtained and compared.
  4. In addition to the above operators, the string does not support other operators by default.

Tags: Python

Posted on Mon, 29 Nov 2021 14:04:46 -0500 by Liquid Fire