Comprehensive understanding of python strings and dictionaries

WBOY
Release: 2016-07-22 08:56:26
Original
1055 people have browsed it

Many sequence method strings are also applicable,
However, strings are immutable, so some methods that attempt to change the string are unavailable

1 String formatting

1) Format string using tuple or dictionary

format = "hello,%s.s% enough for you?"
values ​​= ('world','Hot')
format % values

Similar to C format

2) Template string

The string module provides template strings to format strings
from string import Template
s = Template(x,gloriousx,gloriousx!)
s.substitute(x = 'slurm')
Replace x with slurm
Some detailed tips and usage


Format conversion type, field width precision, sign bit, alignment, padding, etc. Please refer to some manuals


2 String method

1) find

Find substring and return the leftmost index
s.find(subs)

2)join
Connection string

3) lower

4) replace
All matches replaced

5) split
Split string. The delimiter does not contain
.........
..........

-------------------------------------------------- ---

The values ​​in the dictionary are in no particular order

Key can be a number, string, or tuple (must be an immutable type, not a list)

phonebook = {'jmz':'5153','usr1':'1234','usr2':'4321'}

1) dict function

Create a dictionary through other mappings or key-value sequences:
Build a dictionary from a list of 2 tuples:

items = [('key1','value1'),('key2','value2'),('key3','value3')]
d = dict(items)
{'key1':'value1','key2':'value2','key3':'value3'} may not be in this order

Create a dictionary via keyword arguments:
d = dict(key1 = 'value1',key2 = 'value2',key3 = 'value3')
You will also get the above results

The dict function is not a real function, it is a type, similar to list, tuple, and str.

2) Basic dictionary operations

Suppose d is a dictionary:
len(d) dictionary length
d[key]The value of the key key in the dictionary
d[key] = value assignment (key will be added automatically if it does not exist)
del d[key] deletes the item with key key
key in d Check if it is in the dictionary

3) Dictionaries can also be used for formatting

Add the key (in parentheses) after each conversion specifier (%) followed by the other specifiers:
For example: %(value)s
phonebook = {'jmz':'5153','usr1':'10086'}
"jmz's phone number is %(jmz)s." % phonebook
In this way, any number of conversion specifiers can be obtained as long as the given key can be found in the dictionary.

4) Some dictionary methods
clear:
Operate in place (no return value), clear all items in the dictionary

copy: shallow copy and deep copy
y = x.copy()
y = deepcopy(x)

fromkeys:
Creates a new dictionary using the given keys: the default value is None
>>>{}.fromkeys(['key1','key2'])
>>>{'key1':None,'key2':None}
Or:
>>>dict.fromkeys(['key1','key2'])
Same effect

get:
Generally speaking, dictionary entries that are good in the sample essay will be wrong, such as:
>>>print d[name]
And
>>>print d.get('name') will return None by default

has_key:
Return True or False
>>>d.has_key('jmz')

items and iteritems:
The
items method returns the items of the dictionary as a list method:
d = {'key1':'value1','key2':'value2'}
>>>d.items()
>>>[('key1','value1'),('key2','value2')]
iteritems returns the iteration object for items
>>>it = d.iteritems() #it is the iterator object of the above list
>>>list(it)# can convert the iterator into a list
>>>[('key1','value1'),('key2','value2')]

keys and iterkeys:
Return keys as a list, iterator of keys

pop:
d.pop('key') has a return value and removes

popitem:
d.popitem() pops random items because the dictionary is unordered

setdefault:
>>>d.setdefault('key','default_value')
When the key does not exist, return the default value and update the dictionary. If the key already exists, return its value without updating the dictionary, which is equivalent to this sentence having no effect

update:
Use one dictionary to update another dictionary:
>>>d.update(dd)
Add the items in dd to d. If they are repeated, overwrite them.

values ​​and itervalues:
Returns a list of values, an iterator over a list of values.

The above article is all about a comprehensive understanding of Python strings and dictionaries that the editor has shared with you. I hope it can give you a reference, and I hope you will support Script Home.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!