Python string

Note content: Python escape character

Date of Note: 2017-10-24


The basic content of the string has been introduced in the basic data type, so I won't repeat it here.

Python escape characters

When you need to use special characters in a character, Python uses a backslash () to escape the character. The following table:

Among them, \n and \t are the most commonly used, followed by escape quotes and escape backslashes

Python string operators

In the following table, the value of the variable a is the string "Hello", and the value of the b variable is "Python":

a ="Hello"
b ="Python"print("a +b Output result:", a + b)print("a *2 Output result:", a *2) #Output the content of a twice,*n, output the previous string n times
print("a[1]Output result:", a[1]) #Take value from subscript
print("a[1:4]Output result:", a[1:4]) #Intercept string subscript 1-Characters within 4, excluding 4print('hello world'[-1])  #Negative numbers take values in reverse order, so-1 is the value of the last subscript
print('hello world'[0:])  #Start from 0 and take all the following values
print('hello world'[:5])  #Start from 0, intercept to subscript 5if("H"in a):print("H is in variable a")else:print("H is not in variable a")if("M" not in a):print("M is not in variable a")else:text-align: left;print("M is in variable a")print(r'\n')print(R'\n')
# Add an r in front of the print statement to indicate that this is a raw string, which will escape some special characters
print(r'c:\test\abc\123')
# Capitalization is also possible
print(R'c:\test\abc\123')

# You can also write when declaring the string
s=r'c:\test\abc\123'print(s)

operation result:

a + b output: HelloPython
a * 2 Output result: HelloHello
a[1] Output result: e
a[1:4] Output result: ell
H is in variable a
M is not in variable a
 \n
 \n

Among the more commonly used ones are +, *, [], [:] and member operators.

Python string formatting

Python supports the output of formatted strings. Although very complicated expressions may be used in this way, the most basic usage is to insert a value into a string with the string format character %s.
In Python, string formatting uses the same syntax as the printf function in C language. If only simple usage is used, it can be used as printf. Code example:

print("My name is%s this year%d years old!"%('Xiao Ming',10))

operation result:

My name is Xiao Ming and I am 10 years old!

String formatting is seldom used. It’s a tasteless thing. Just know if there is such a thing.

Python string formatting symbols:

Formatting operator auxiliary instructions:

Python triple quotation marks

Python triple quotation marks allow a string to span multiple lines. The string can contain line breaks, tabs and other special characters. Code examples:

para_str ="""This is an example of a multi-line string
Multi-line strings can use tabs
TAB( \t )。
Line breaks can also be used[ \n ]。
"""
print(para_str)

operation result:

This is an example of a multi-line string
Multi-line strings can use tabs
 TAB (    )。
You can also use line breaks [
  ]。

Python's string built-in functions

The commonly used built-in functions of Python strings are as follows:

Serial number Method and description
1 capitalize() converts the first character of the string to uppercase
2 center(width, fillchar) returns a string with the specified width in the center, fillchar is the filled character, and the default is a space.
3 count(str, beg= 0,end=len(string)) returns the number of occurrences of str in string, if beg or end is specified, returns the number of occurrences of str within the specified range. Capital
4 bytes.decode(encoding=”utf-8”, errors=”strict”) There is no decode method in Python3, but we can use the decode() method of the bytes object to decode a given bytes object. This bytes object can be used by str. encode() to encode the return.
5 encode(encoding='UTF-8',errors='strict') Encode the string in the encoding format specified by encoding. If an error occurs, a ValueError exception will be reported by default, unless errors specify'ignore' or'replace'
6 ceendswith(suffix, beg=0, end=len(string)) Check whether the string ends with obj, if beg or end is specified, check whether the specified range ends with obj, if yes, return True, otherwise return False.
7 expandtabs(tabsize=8) converts the tab symbol in the string to spaces. The default number of spaces for the tab symbol is 8.
8 find(str, beg=0 end=len(string)) Check whether str is contained in the string. If the range beg and end are specified, check whether it is contained within the specified range. If it contains, return the starting index value, otherwise return- 1
9 index(str, beg=0, end=len(string)) is the same as the find() method, except that an exception will be reported if str is not in the string.
10 isalnum() returns True if the string has at least one character and all characters are letters or numbers, otherwise it returns False
11 isalpha() returns True if the string has at least one character and all characters are letters, otherwise it returns False
12 isdigit() returns True if the string contains only digits, otherwise returns False..
13 islower() If the string contains at least one case-sensitive character, and all these (case-sensitive) characters are lowercase, it returns True, otherwise it returns False
14 isnumeric() If the string contains only numeric characters, it returns True, otherwise it returns False
15 isspace() If the string contains only blanks, it returns True, otherwise it returns False.
16 istitle() returns True if the string is titled (see title()), otherwise it returns False
17 isupper() If the string contains at least one case-sensitive character, and all these (case-sensitive) characters are uppercase, it returns True, otherwise it returns False
18 join(seq) takes the specified string as the separator, and merges all the elements (the string representation) in seq into a new string
19 len(string) returns the length of the string
20 ljust(width[, fillchar]) returns a new string with the original string left-justified and filled to the length width with fillchar. The fillchar defaults to a space.
21 lower() converts all uppercase characters in the string to lowercase.
22 lstrip() cuts off the spaces or specified characters on the left side of the string.
23 maketrans() creates a conversion table of character mapping. For the simplest calling method that accepts two parameters, the first parameter is a string, which indicates the character to be converted, and the second parameter is also a string that indicates the target of the conversion.
24 max(str) returns the largest letter in the string str.
25 min(str) returns the smallest letter in the string str.
26 replace(old, new [, max]) Replace str1 in the string with str2. If max is specified, the replacement will not exceed max times.
27 rfind(str, beg=0,end=len(string)) is similar to the find() function, but searches from the right.
28 rindex(str, beg=0, end=len(string)) is similar to index(), but starts from the right.
29 rjust(width, [, fillchar]) returns a new string with the original string right-justified and filled to the length width with fillchar (default space)
30 rstrip() removes the spaces at the end of the string.
31 split(str=””, num=string.count(str)) num=string.count(str)) Use str as the separator to intercept the string. If num has a specified value, only num substrings will be intercepted
32 splitlines([keepends]) is separated by lines ('\r','\r\n', \n') and returns a list containing each line as an element. If the parameter keepends is False, no line breaks are included. If it is True , The newline character is retained.
33 startswith(str, beg=0,end=len(string)) checks whether the string starts with obj, if yes, it returns True, otherwise it returns False. If beg and end specify values, check within the specified range.
34 strip([chars]) performs lstrip() and rstrip() on the string
35 swapcase() converts uppercase to lowercase and lowercase to uppercase in a string
36 title() returns a "titled" string, which means that all words start with uppercase and the rest of the letters are lowercase (see istitle())
37 translate(table, deletechars=””) converts the characters of string according to the table (containing 256 characters) given by str, and puts the characters to be filtered out in the deletechars parameter
38 upper() converts lowercase letters in a string to uppercase
39 zfill (width) returns a string of length width, the original string is right-aligned, and the front is filled with 0
40 isdecimal() checks whether the string contains only decimal characters, and returns true if it is, otherwise it returns false.

Several commonly used function code examples:

s ="hello..."
upper ="HELLO..."print("Convert the first character of s to uppercase:", str.capitalize(s))print("Number of occurrences of'l' in s:", s.count("l"))print("Does it end with '...'end:", s.endswith("..."))print("Does it end with 'h’开头:", s.startswith("h"))print("The subscript of'o' in s is (if not found, it will return-1):", s.find("o"))print("The subscript of'o' in s is (if not found, an exception will be thrown):", s.index("o"))print("Replace the'o' of s with'c':", s.replace("o","c"))print("The largest letter in s is:",max(s))print("The smallest letter in s is:",min(s))print("Convert upper to lowercase:", upper.lower())print("Convert s to uppercase:", s.upper())print("Titleize s:", s.title())

seq =("a","b","c","d","e")  #String sequence
print("Combine the characters in seq:","".join(seq))print("The length of seq is:",len(seq))  #String sequences can also be used
print("The length of s is:",len(s))

s2 ="a,b,c,d,e,f,g"print("Separate the strings in s2 by commas", s2.split(","))

s3 ="This is swapcase method test"print("Convert the uppercase of the string in s3 to lowercase and lowercase to uppercase:", s3.swapcase())

s4 ="    Test      "print("Remove the left and right spaces of s4:", s4.strip())

operation result:

Convert the first character of s to uppercase: Hello...
Number of occurrences of'l' in s: 2
Does s end with "...": True
Whether to start with'h' in s: True
The subscript of'o' in s is (if not found, it will return -1): 4
The subscript of'o' in s is (if not found, an exception will be thrown): 4
Replace the'o' of s with'c': hellc...
The largest letter in s is: o
The smallest letter in s is:.
Convert upper to lowercase: hello...
Convert s to uppercase: HELLO...
Title s: Hello...
Combine characters in seq: abcde
The length of seq is: 5
The length of s is: 8
Separate the strings in s2 by commas ['a','b','c','d','e','f','g']
Convert the uppercase of the string in s3 to lowercase and lowercase to uppercase: tHIS IS SWAPCASE METHOD TEST
Remove the left and right spaces of s4: Test

Recommended Posts

Python string
Python string
Str string in Python
How Python converts string case
Python interview questions: string concatenation
Python string three formatted output
Python multithreading
Python CookBook
Python FAQ
Python3 dictionary
Python3 module
Python basics
Python descriptor
Python basics 2
Python implements string and number splicing
Python exec
Python notes
Python3 tuple
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python IO
Python multithreading
Python toolchain
Python3 list
Python multitasking-coroutine
Python overview
python introduction
Python analytic
Python basics
07. Python3 functions
Python basics 3
Python multitasking-threads
Python functions
python sys.stdout
python operator
Python entry-3
The premise of Python string pooling
Centos 7.5 python3.6
python queue Queue
Python basics 4
Python basics 5
Python classic programming questions: string replacement
Python string to judge the password strength
Centos6 install Python2.7.13
Python basic syntax (1)
Python exit loop
Ubuntu16 upgrade Python3
Centos7 install Python 3.6.
ubuntu18.04 install python2
Relearn ubuntu --python3
Python2.7 [Installation Tutorial]
Python 3.9 is here!
Python study notes (1)
python learning route
CentOS7 upgrade python3
Python3 basic syntax
Python review one
linux+ubuntu solve python
Functions in python
Python learning-variable types