0x01 String
Strings are the most commonly used data type in Python, and both single and double quotes are supported. Single quotes are used to print strings when double quotes are used.
>>> "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 be used to escape quotes using a backslash (\).
>>> 'Let\'s go!' "Let's go!" >>> "\"Hello, world!\" she said" '"Hello, world!" she said'
splice a string
It is common to use the + sign to concatenate strings, like adding numbers.
>>> "she said " + '"Hello world!"' 'she said "Hello world!"' >>> a = "she said " >>> b = '"Hello world!"' >>> a + b 'she said "Hello world!"'
String splicing is also possible when two strings are entered sequentially.
>>> "she said " '"Hello world!"' 'she said "Hello world!"' # Useful only if the input is a string >>> a = "she said " >>> b = '"Hello world!"' >>> a b File "<stdin>", line 1 a b ^ SyntaxError: invalid syntax
long string
Triple quotes can be used to indicate 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. Backslashes and newlines will be escaped, i.e. ignored, as long as a backslash is added at the end of the line.
>>> 1 + 2 + \ 4 + 5 12 >>> print("Hello \ world!") Hello world! >>> print \ ('Hello world') Hello world
Indexing
For string literals, you can perform indexing operations on them directly without assigning them to variables first.
>>> 'Hello'[1] 'e'
If a function call returns a sequence, you can perform indexing operations on it directly.
>>> yearnum = input('please input year: ')[3] please input year: 2021 >>> yearnum '1'
When multiplying a sequence by the number n, the sequence will be repeated n times to create a new sequence.
>>> 'python' * 3 'pythonpythonpython'
The operator in
To check whether a particular value is included in a 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
Creating Lists
Use the function list , you can quickly convert a string into a list of characters.
>>> somelist = list('Hello') >>> somelist ['H', 'e', 'l', 'l', 'o']
Converts a list of characters to a string.
>>>''.join(somelist)
Slice Assignment
>>> name = list('Perl') >>> name ['P', 'e', 'r', 'l'] >>> name[2:] = list('ar') >>> name ['P', 'e', 'a', 'r'] >>> name = list('Perl') >>> name[1:] = list('ython') >>> name ['P', 'y', 't', 'h', 'o', 'n']
0x02 String Formatting
The %s in the format string is called the conversion specifier and indicates where to insert the value and specifies the value to format on the right. Specifying the value whose format is to be set can be done with a single value (such as a string or number), with a tuple (if multiple values are to be formatted), or with a dictionary, the most common of which is a tuple.
>>> format = "Hello, %s. %s !" >>> values = ('world', 'python') >>> format % values 'Hello, world. python !'
Template String
Parameters that contain an equal sign are called keyword parameters, the
>>> from string import Template >>> tmpl = Template("Hello, $param1! $param2 !") >>> (param1="world", param2="Python") 'Hello, world! Python !'
String method format
>>> "{}, {} and {}".format("first", "second", "third") 'first, second and third' >>> "{0}, {1} and {2}".format("first", "second", "third") 'first, second and third' >>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to") 'to be or not to be' >>> from math import pi >>> "{name} approximately equal to {value:.2f}.".format(value=pi, name="π") 'π is approximately equal to 3.14.''
There is also a shorthand that can be used if the variable has the same name as the replacement field. In this case, use the f string - precede the string with f. (Python 3.6+)
>>> from math import e >>> f"Euler's constant is roughly {e}." # Equivalent to "Euler's constant is roughly {e}.".format(e=e) "Euler's constant is roughly 2.718281828459045."
0x03 How to set the format
The string contains information about how to format it, which is specified using a mini-language. Each value is inserted into the string to replace the replacement field enclosed in parentheses. The replacement field consists of the following parts, each of which is optional.
- Field name: An index or identifier that indicates which value to format and use the result to replace the field. In addition to specifying a value, you can also specify a specific part of the value, such as an element of a list.
- Conversion flag: a single character followed by an exclamation point. Currently supported characters are r (for repr), s (for str) and a (for ascii). If you specify the conversion flag, you will not use the formatting mechanism of the object itself, but use the specified function to convert the object to a string and then do further formatting.
- Format specifier: An expression followed by a colon (such expressions are expressed in a mini-formatting language). Format specifiers allow us to specify the final format in detail, including the type of format (such as string, float, or hexadecimal), the width of the field and the precision of the number, how to display symbols and thousands separators, and the various types of alignment and padding.
field name
Simply provide format with the unnamed parameter to be formatted and use the unnamed field in the format string. The fields and parameters will then be paired sequentially. You can also assign names to the parameters, which will be used in the corresponding replacement fields. You can use a mixture of these two methods.
>>> "{foo} {} {bar} {}".format(1, 2, bar=4, foo=3) '3 1 4 2'
You can also specify which field to use the corresponding unnamed parameter in by using the index, so that the unnamed parameters can be used out of order.
>>> "{foo} {1} {bar} {0}".format(1, 2, bar=4, foo=3) '3 2 4 1'
Instead of being able to use the supplied value itself, you can access its components, use indexes, and use syntax to access methods, properties, variables, and functions in the imported module.
>>> fullname = ["Alfred", "Smoketoomuch"] >>> "Mr {name[1]}".format(name=fullname) 'Mr Smoketoomuch' >>> import math >>> tmpl = "The {mod.__name__} module defines the value {} for π" >>> (mod=math) 'The math module defines the value 3.141592653589793 for π'
transition mark
(s, r, and a) specifies the use of str, repr, and ascii for conversion, respectively. The str function usually creates a plain-looking version of the string \. The repr function attempts to create a Python representation of a given value (in this case a string literal). The ascii function creates an ASCII-only representation.
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π")) π 'π' '\u03c0'
Format description
(i.e., after the colon) use the character f (for fixed point).
>>> "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 Methods
constant
A few useful constants in the module string
- : A string containing the numbers 0 through 9.
- string.ascii_letters: a string containing all ASCII letters (upper and lower case).
- string.ascii_lowercase: string containing all lowercase ASCII letters.
- : A string containing all printable ASCII characters.
- : A string containing all ASCII punctuation characters.
- string.ascii_uppercase: string containing all uppercase ASCII letters.
Filling method
String Fill Character Method
center、 ljust、 rjust、 zfill
split
If no separator is specified, splitting will occur by default at one or more consecutive white space characters (spaces, tabs, line feeds, etc.)
>>> seq = ['1', '2', '3', '4', '5'] >>> sep = '+' >>> ('+') # Merge a 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']
Above is the details of how to properly manipulate strings in python, for more information about python manipulate strings please follow my other related articles!