python How to Manipulate Strings Correctly

  • 2021-11-13 02:05:11
  • OfStack

Directory 0x01 String (string) Quotation mark escape
Splice string
Long string
Index (indexing)
Operator in
Create a list
Slice assignment 0x02 string formatting Template string
How to Format String Method format0x03 Field name
Conversion flag
Format description
0x04 String Method Constant
Filling method
split

0x01 String (string)

String is the most commonly used data type in Python and supports both single and double quotation marks. When using double quotation marks, use single quotation marks when printing strings.


>>> "Hello world!"
'Hello world!'

>>> 'Hello  world!'
'Hello  world!'

>>> "Let's go!"
"Let's go!"

>>> 'she said "Hello world!" '
'she said "Hello, world!" '

Quotation mark escape

The above example can use a backslash (\) to escape quotation marks.


>>> 'Let\'s go!'
"Let's go!"

>>> "\"Hello, world!\" she said"
'"Hello, world!" she said'

Splice string

Usually, strings are spliced with + signs, just like numbers added to 1.


>>> "she said " + '"Hello world!"'
'she said "Hello world!"'

>>> a = "she said "
>>> b = '"Hello world!"'
>>> a + b
'she said "Hello world!"'

String splicing can also be realized when two strings are entered in turn.


>>> "she said " '"Hello world!"'   
'she said "Hello world!"'

#  It is only useful if you enter a string 
>>> a = "she said "
>>> b = '"Hello world!"'
>>> a  b
  File "<stdin>", line 1
    a  b
       ^
SyntaxError: invalid syntax

Long string

You can use 3 quotation marks to represent very long strings (strings that span multiple lines).


>>> """like this"""
'like this'

>>> print('''long long ago!
"Hello world!"
she said.''')
long long ago!
"Hello world!"
she said. 

Regular strings can also span multiple lines. As long as a backslash is added at the end of a line, the backslash and line break will be escaped and ignored.


>>> 1 + 2 + \
4 + 5
12

>>> print("Hello  \
 world!")
Hello  world!

>>> print \
('Hello  world')
Hello  world

Index (indexing)

For string literals, you can index them directly without first assigning them to variables.


>>> 'Hello'[1]
'e'

If the function call returns 1 sequence, it can be indexed directly.


>>> yearnum = input('please input year: ')[3]
please input year: 2021
>>> yearnum
'1'  

When the sequence is multiplied by the number n, the sequence n is repeated to create a new sequence.


>>> 'python' * 3 
'pythonpythonpython'

Operator in

To check whether a particular value is included in the sequence, use the operator in


>>> access_mode = 'rw+'
>>> 'w' in access_mode 
True
>>> 'x' in access_mode 
False

>>> subject = '$$$ Get rich now!!! $$$'
>>> '$$$' in subject 
True

Create a list

Using the function list, you can quickly convert a string into a 1-character list.


>>> 'Let\'s go!'
"Let's go!"

>>> "\"Hello, world!\" she said"
'"Hello, world!" she said'
0

Converts a list of characters to a string.


>>> 'Let\'s go!'
"Let's go!"

>>> "\"Hello, world!\" she said"
'"Hello, world!" she said'
1

Slice assignment


>>> 'Let\'s go!'
"Let's go!"

>>> "\"Hello, world!\" she said"
'"Hello, world!" she said'
2

0x02 String Formatting

The% s in the format string is called the conversion specifier, which indicates where to insert the value and specifies the value to be formatted on the right. When specifying a value to format, you can use a single value (such as a string or number), tuples (if you want to format multiple values), and dictionaries, the most common of which is tuples.


>>> format = "Hello, %s. %s !"
>>> values = ('world', 'python')
>>> format % values 
'Hello, world. python !'

Template string

Parameters that contain the equal sign are called keyword parameters,


>>> 'Let\'s go!'
"Let's go!"

>>> "\"Hello, world!\" she said"
'"Hello, world!" she said'
4

String method format


>>> 'Let\'s go!'
"Let's go!"

>>> "\"Hello, world!\" she said"
'"Hello, world!" she said'
5

If the variable has the same name as the replacement field, you can also use 1 abbreviation. In this case, use the f string--precede the string with f. (Python 3.6 +)


>>> 'Let\'s go!'
"Let's go!"

>>> "\"Hello, world!\" she said"
'"Hello, world!" she said'
6

0x03 How to Format

The string contains information about how to format, which is specified using a microformat specification language (mini-language). Each value is inserted into the string to replace the replacement field enclosed in curly braces. The replacement field consists of the following parts, each of which is optional.

Field name: Index or identifier that indicates which value to format and replaces the field with the result. In addition to specifying values, you can also specify specific parts of values, such as elements of a list. Conversion flag: A single character following an exclamation point. The currently supported characters include r (for repr), s (for str), and a (for ascii). If you specify the conversion flag, instead of using the formatting mechanism of the object itself, you will use the specified function to convert the object to a string, and then do the formatting step further. Format specifier: An expression that follows a colon (this expression is expressed in a microformat specifying language). Format specifiers allow us to specify the final format in detail, including format types (such as strings, floating-point numbers, or 106-ary numbers), field widths and number precision, how symbols and thousand separators are displayed, and various alignment and padding methods.

Field name

Simply supply the format with the unnamed parameters that you want to format and use the unnamed fields in the format string. At this point, the fields and parameters are paired in sequence. You can also specify a name for the parameter, which will be used in the corresponding replacement field. You can mix the two methods.


>>> 'Let\'s go!'
"Let's go!"

>>> "\"Hello, world!\" she said"
'"Hello, world!" she said'
7

You can also use the index to specify in which field you want to use the corresponding unnamed parameters, so that you can use unnamed parameters out of order.


>>> "{foo} {1} {bar} {0}".format(1, 2, bar=4, foo=3) 
'3 2 4 1'

Instead of using only the supplied value itself, you can access its components, use indexes, and use period notation to access methods, properties, variables, and functions in the imported module


>>> 'Let\'s go!'
"Let's go!"

>>> "\"Hello, world!\" she said"
'"Hello, world!" she said'
9

Conversion flag

(s, r, and a) specifies that str, repr, and ascii are used for conversion, respectively. The function str usually creates a plain-looking string version\. The function repr attempts to create an Python representation of the given value (in this case, a string literal). The function ascii creates a representation that contains only ASCII characters.


>>> print("{pi!s} {pi!r} {pi!a}".format(pi=" π ")) 
 π  ' π ' '\u03c0'

Format description

(that is, after the colon) uses the character f (for the fixed point number).


>>> "The number is {num}".format(num=42) 
'The number is 42'
>>> "The number is {num:f}".format(num=42) 
'The number is 42.000000'
>>> "The number is {num:b}".format(num=42) 
'The number is 101010'

0x04 String Method

Constant

Several useful constants in module string

string. digits: A string containing the numbers 0 through 9. string. ascii_letters: A string containing all ASCII letters (uppercase and lowercase). string. ascii_lowercase: A string containing all lowercase ASCII letters. string. printable: A string containing all printable ASCII characters. string. punctuation: A string containing all ASCII punctuation characters. string. ascii_uppercase: A string containing all uppercase ASCII letters.

Filling method

String filling character method

center, ljust, rjust, zfill

split

If no delimiter is specified, splitting is performed by default at a single or multiple consecutive white space characters (spaces, tabs, newlines, and so on)


>>> seq = ['1', '2', '3', '4', '5']
>>> sep = '+'
>>> sep.join('+') #  Merge 1 List of strings 
'1+2+3+4+5'

>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> 'Using the default'.split()
['Using', 'the', 'default']

The above is python how to correctly manipulate the string details, more information about python manipulation string please pay attention to other related articles on this site!


Related articles: