Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky

Definition of a string

A string is a finite sequence of zero or more characters.

In Python programs, we can represent a string by wrapping single or more characters around single or double quotation marks, or by folding three single or double quotation marks. The characters of the string can be special symbols, English letters, Chinese characters, Hiragana or Katakana in Japanese, Greek letters, Emoji characters, and so on.

The following code shows strings in Python:

text1 = "This is a string wrapped in double quotes."
text2 = 'This is a string wrapped in single quotes.'
text3 = """ "This is the string that's wrapped in three quotes and you can keep it the way it was. ""

print(text1)
print(text2)
print(text3)

Copy the code

The code results are as follows:

So this is the string that's wrapped in double quotes and this is the string that's wrapped in single quotes and this is the string that's wrapped in three quotes and you can keep it the way it wasCopy the code

Escape strings and raw strings

Python uses the backslash “” to indicate an escape, which means that the following content is not the original content. For example, \n means a newline instead of the and character n; Therefore, if the string itself contains special characters such as’, “, and so on, it must be escaped through ‘.

The sample code looks like this:

text1 = "\'Hello world\'"  # Print Hello World wrapped in single quotes
text2 = '\\Hello world\\'  Print Hello World wrapped with two backslashes


print(text1)
print(text2)

Copy the code

Here are some escape characters in Python:

Escape character describe
(At the end of the line) Line continuation operator
\ Backslash notation
' Single quotes
" Double quotation marks
\a Ring the bell
\b Backspace (Backspace)
\ 000 empty
\n A newline
\v Vertical TAB character
\t Horizontal tabs
\r enter
\f Change the page
\oyy Octal number,yyRepresents a character, for example:\o12Stands for newline, where o is a letter, not the number 0.
\xyy A hexadecimal number, yy represents a character, for example, \x0a represents a newline
\other Other characters are printed in normal format

Primitive strings are a special class of strings in Python that begin with either uppercase R or lowercase R. In the raw string, the character “\” no longer represents the meaning of an escape character.

The sample code looks like this:

text1 = "Since ancient times, those who made great achievements had not only extraordinary talents, but also indomitable ambition."
text2 = R "Since ancient times, those who made great achievements had not only extraordinary talents, but also great perseverance."

print(text1)
print(text2)
Copy the code

Run the code as follows:

In ancient times, those who accomplished great things not only had extraordinary talents, but also had firm and indomitable willsCopy the code

String operation

Python provides a large number of operators for string types

Concatenation operator

The + operator is used to concatenate strings, and the * operator is used to repeat the contents of a string

text1 = "Hello,world"
text2 = "!"
print(text1 + text2)  # Hello,world!
print(text2 * 10)  #!!!!!!!!!!!!!!!!!!!!!!!!!
Copy the code

It is important to use * to implement string repetition. For example, to print a separator line as ————— is cumbersome, but using – * 20 is easy

Members of the operation

In and not in can be used in Python to determine the presence of another character or string in a string. The in and not in operations, often called member operations, yield Boolean values True or False

text1 = "Hello,world"
text2 = "Bowl week."
print("llo" in text1)  # True
print("Week" not in text2)  # False
print("Porridge" not in text2)  # True
Copy the code

Get the length of the string

The length of a character is obtained by the built-in function len()

text1 = "Hello,world"
text2 = "Bowl week."
print(len(text1))  # 11
print(len(text2))  # 3

Copy the code

Index and slice

If you reference a character in a string, you can index the character from. The Python index starts at 0), the operator is [n], where n is an integer, assuming the string length is n, then n can be an integer from 0 to n-1, where 0 is the index of the first character in the string and n-1 is the index of the last character in the string, usually called a forward index; In Python, strings can also be indexed as integers from -1 to -n, where -1 is the index of the last character and -n is the index of the first character, often referred to as a negative index.

It is worth noting that because strings are immutable, you cannot modify characters in a string through an index operation.

text1 = "Hello,world"
text2 = "Bowl week."
N1 = len(text1)
N2 = len(text2)
Get the first character
print(text1[0], text1[-N1])  # H H
print(text2[0], text2[-N2])  # a a
Get the last character
print(text1[N1 - 1], text1[-1])  # d d
print(text2[N2 - 1], text2[-1])  # week week
Get the characters with indexes 2 and -2
print(text1[2], text1[-2])  # l l
print(text2[2], text2[-2])  # weeks bowl

Copy the code

Note: An error can occur if the index is out of bounds (that is, the index value is not in the index range), for example

print(text2[222])
Copy the code

The error message is as follows:

IndexError: String index out of range #Copy the code

To extract multiple characters, slice the string with the operator [I :j:k], where I is the starting index. The corresponding character of the index can be n-1 or -1. J is the end index. The corresponding character of the index cannot be 0 or -n. K is the step length, and the default value is 1, which indicates the continuous slice of adjacent characters from front to back (can be omitted). If the value of k is a positive number, it is a forward index. If k is a negative value, it is a negative index.

s = '123456789abcdef, a bowl of weeks'
# I =3, j=6, k=1 forward slice operation
print(s[3:6])       # 456

# I =-17, j=-14, k=1 forward slice operation
print(s[-17: -14])     # 456

# I =16, j= default, k=1 forward slice operation
print(s[16:)# a bowl of weeks

# I =-4, j= default, k=1 forward slice operation
print(s[-3:)# a bowl of weeks

# I =8, j= default, k=2 forward slice operation
print(s[8: :2])      # 9 BDF for a week

# I =-12, j= default, k=2 forward slice operation
print(s[-12: :2])     # 8 ace, bowl

# I = default, j= default, k=2 forward slice operation
print(s[::2])       # 13579 BDF for a week

# I = default, j= default, k=1 forward slice
print(s[:])         # 123456789abcdef, one bowl week

# I =1, j=-1, k=2 forward slice operation
print(s[1: -1:2])    # 2468 ace, bowl

print("-"*20)

# I =7, j=1, k=-1 negative slice operation
print(s[7:1: -1])    # 876543

# I =-13, j=-19, k=-1 negative slice operation
print(s[-13: -19: -1])  # 876543

# I =8, j= default, k=-1 negative slice operation
print(s[8: : -1])     # 987654321

# I = default, j=1, k=-1 negative slice operation
print(s[:15: -1])     A week of # bowl

# I = default, j= default, k=-1 negative slice
print(s[::-1])      # Week Bowl 1, fedcba987654321

# I = default, j= default, k= negative slice of -2
print(s[::-2])      # fdb97531 Monday

Copy the code

The default value of I is the beginning number, and the default value of j is the end number (including itself).

Note that the string returned includes I but not j.

String methods

In Python, strings are handled and manipulated using methods that come with their types. For a string variable, the variable name is used. Method name () to call its method. A method is a function bound to a variable of a type.

Change case

s1 = 'hello, world! '

Capitalize the capitalize method to obtain the string capitalize the first letter of the string
print(s1.capitalize())   # Hello, world!
Use the title method to get the string after each word is capitalized
print(s1.title())        # Hello, World!
Use the upper method to get the string capitalized
print(s1.upper())        # HELLO, WORLD!

s2 = 'GOODBYE'
Use the lower method to get the string after lowercase
print(s2.lower())        # goodbye

Copy the code

Find operations

If you want to look backwards in a string to see if there is another string, you can use the find or index methods of the string.

s = 'hello, world! '

The # find method finds the location of another string within a string
# found an index that returns the first character of another string in a string
print(s.find('or'))        # 8
Return -1 if not found
print(s.find('shit'))      # 1
The # index method is similar to find
# found an index that returns the first character of another string in a string
print(s.index('or'))       # 8
No throw exception found
print(s.index('shit'))     # ValueError: substring not found

Copy the code

When you use the find and index methods, you can also specify the scope of the search through the parameters of the method, without having to start at index 0. The find and index methods also have backward versions, called rfind and rindex, respectively

s = 'hello good world! '

# find the position of the character o from front to back
print(s.find('o'))       # 4
# search for the occurrence of character o starting at index 5
print(s.find('o'.5))    # 7
# find the last occurrence of the character o from back to forward.
print(s.rfind('o'))      # 12
Copy the code

The nature of the judgment

You can determine whether a string starts or endswith a string by startswith and endswith. You can also determine the character of a string using methods starting with IS, which all return a Boolean value.

s1 = 'hello, world! '

The # startwith method checks if the string returns a Boolean value starting with the specified string
print(s1.startswith('He'))    # False
print(s1.startswith('hel'))   # True
The # endswith method checks if the string returns a Boolean value at the end of the specified string
print(s1.endswith('! '))       # True

s2 = 'abc123456'

The # isDigit method checks if the string is composed of numbers and returns a Boolean value
print(s2.isdigit())    # False
The # isalpha method checks if the string returns a Boolean value in alphabetic form
print(s2.isalpha())    # False
The # isalnum method checks if the string returns a Boolean value in the form of numbers and letters
print(s2.isalnum())    # True

Copy the code

Formatted string

In Python, string types can be centered, left-aligned, and right-aligned using the Center, ljust, and rjust methods.

s = 'hello, world'

The # center method centers the string with a width of 20 and fills both sides with *
print(s.center(20.The '*'))  # ****hello, world****
The # rjust method right-aligns the string with a width of 20 and fills the left side with Spaces
print(s.rjust(20))        # hello, world
The # ljust method left-aligns the string with a width of 20 and populates it with ~ on the right
print(s.ljust(20.'~'))   # hello, world~~~~~~~~
Copy the code

Python2.6 has added a str.format() function to format strings, which enhances string formatting.

The basic syntax is to replace the previous % with {} and:.

a = 111
b = 222
print('{0} + {1} = {2}'.format(a, b, a + b)) # 111 + 222 = 333
c = "hello"
d = "world"
# do not set the specified location, in default order
print("{} {}".format(c, d))        # hello world
print("{0} {1}".format(c, d))      # hello world
print("{1} {0}".format(d, c))      # hello world
print("{1} {0} {1}".format(c, d))  # world hello world
Copy the code

Starting in Python 3.6, there is a more concise way to format a string by prefixing it with an f. In such f strings, {variable name} is a placeholder that will be replaced by the value of the variable.

a = 111
b = 222
print(f"{a} + {b} = {a + b}") # 111 + 222 = 333
c = "hello"
d = "world"
print(f"{c} {d}")        # hello world
Copy the code

Multiple operations on number formatting

digital format The output describe
3.1415926 {:.2f} 3.14 Keep two decimal places
3.1415926 {:+.2f} + 3.14 The sign preserves two decimal places
– 1 {:+.2f} 1.00 The sign preserves two decimal places
2.71828 {:.0f} 3 With no decimal
5 {:0>2d} 05 Numeric zeroing (padding left, width 2)
5 {:x<4d} 5xxx Number fill x (fill right side, width 4)
10 {:x<4d} 10xx Number fill x (fill right side, width 4)
1000000 {:} 1000000 Number format separated by commas
0.25 } {: 2% 25.00% Percentage format
1000000000 {:.2e} 1.00 e+09 Index notation
13 {:>10d} 13 Right aligned (default, width 10)
13 {:<10d} 13 Left aligned (width 10)
13 {:^10d} 13 Middle alignment (width 10)
11 '{:b}'.format(11)<br>'{:d}'.format(11)

'{:o}'.format(11)

'{:x}'.format(11)<br>'{:#x}'.format(11)

'{:#X}'.format(11)
1011<br> 11<br> 13<br>b<br>0xb<br>0XB Into the system

The values are center, left, and right aligned, followed by a width, and padded with a colon (:). The value can be only one character. If this parameter is not specified, it is padded with a space by default.

+ indicates that + is displayed before positive numbers and – before negative numbers; (space) Indicates that space b, D, o, and x are binary, decimal, octal, and hexadecimal digits respectively.

Pruning operation

The strip() method is used to remove the string and trim off specified characters (defaults to Spaces or newlines) or sequences of characters. This method is very useful and is often used to remove the leading and trailing Spaces that the user accidentally typed in. There are two versions of the strip method: Lstrip (left strip) and Rstrip (right strip).

s = 'A bowl of chow \t\n'
The # strip method gets the string after the left and right whitespace trim
print(s.strip())    # a bowl of weeks

s1 = "!!! A bowl of weeks!!!!!!"
print(s1.lstrip("!"))  # Bowl week!!
print(s1.rstrip("!"))  #!!!!!! A bowl of weeks

Copy the code