Article directory
execute string
Using Python's built-in eval function, you can execute Python code in a string. In this way, strings can be converted into other types of data.
x = '1+1'
print(eval(x)) # 2
print(type(eval(x))) # <class 'int'>
y = '{"name":"zhangsan","age":18}'
print(eval(y))
print(type(eval(y))) # <class 'dict'>
print(eval('1 > 2')) # False
eval('input("请输入您的姓名:")')
convert to string
JSON (JavaScript Object Notation, JS Object Notation) is a lightweight data exchange format based on a subset of ECMAScript, which uses a text format completely independent of programming languages to store and represent data. JSON is essentially a string
JSON has powerful functions and a wide range of usage scenarios. At present, we only introduce how to use Python's built-in JSON module to realize the mutual conversion between dictionaries, lists, or tuples and strings.
Using the dumps method of json, you can convert dictionaries, lists or tuples into strings.
import json
person = {
'name': 'zhangsan', 'age': 18}
x = json.dumps(person)
print(x) # {"name": "zhangsan", "age": 18}
print(type(x)) # <class 'str'>
nums = [1, 9, 0, 4, 7]
y = json.dumps(nums)
print(y) # [1, 9, 0, 4, 7]
print(type(y)) # <class 'str'>
words = ('hello','good','yes')
z = json.dumps(words)
print(z) # ["hello", "good", "yes"]
print(type(z)) # <class 'str'>
Use the loads method of json to convert a properly formatted string into a dictionary or list.
x = '{"name": "zhangsan", "age": 18}'
person = json.loads(x)
print(person) # {'name': 'zhangsan', 'age': 18}
print(type(person)) # <class 'dict'>
y = '[1, 9, 0, 4, 7]'
nums = json.loads(y)
print(nums) # [1, 9, 0, 4, 7]
print(type(nums)) # <class 'list'>
What strings, lists, tuples, dictionaries and sets have in common
Strings, lists, tuples, dictionaries, and collections have many similarities. They are all iterable objects composed of multiple elements, and they all have some methods that can be used in common.
arithmetic operator
In Python, some common arithmetic operators can be used on iterable objects, and their execution results are slightly different.
operator | Python expression | result | describe | Supported data types |
---|---|---|---|---|
+ | [1, 2] + [3, 4] | [1, 2, 3, 4] | merge | string, list, tuple} |
- | {1,2,3,4} - {2,3} | {1,4} | set difference | gather |
* | [‘Hi!’] * 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | copy | string, list, tuple |
in | 3 in (1, 2, 3) | True | element exists | strings, lists, tuples, dictionaries |
not in | 4 not in (1, 2, 3) | True | element does not exist | strings, lists, tuples, dictionaries |
+
The addition operator can be used on strings, lists and tuples to concatenate multiple iterable objects, but not on dictionaries and sets.
>>> "hello " + "world"
'hello world'
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> ('a', 'b') + ('c', 'd')
('a', 'b', 'c', 'd')
-
Subtraction can only be used in sets to find the difference between two sets.
>>> {
1, 6, 9, 10, 12, 3} - {
4, 8, 2, 1, 3}
{
9, 10, 12, 6}
*
The addition operator can be used on strings, lists, and tuples to iterate an iterable multiple times, and it cannot be used on dictionaries and sets.
>>> 'ab' * 4
'ababab'
>>> [1, 2] * 4
[1, 2, 1, 2, 1, 2, 1, 2]
>>> ('a', 'b') * 4
('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')
in
The in and not in member operators can be used on all iterable objects. But it should be noted that when in and not in judge the dictionary, they check whether the specified key exists, not the value.
>>> 'llo' in 'hello world'
True
>>> 3 in [1, 2]
False
>>> 4 in (1, 2, 3, 4)
True
>>> "name" in {
"name":"chris", "age":18}
True
traverse
Through for ... in ... we can traverse iterable objects such as strings, lists, tuples, dictionaries, and collections.
string traversal
a_str = "hello world"
for char in a_str:
print(char,end=' ')
list traversal
a_list = [1, 2, 3, 4, 5]
for num in a_list:
print(num,end=' ')
tuple traversal
a_turple = (1, 2, 3, 4, 5)
for num in a_turple:
print(num,end=" ")
subscripted traversal
Iterable objects can be wrapped into an enumerate object using the enumerate built-in class. By traversing enumerate, you can get the subscript and elements of an iterable object at the same time.
nums = [12, 9, 8, 5, 4, 7, 3, 6]
# 将列表nums包装成enumerate对象
for i, num in enumerate(nums): # i表示元素下标,num表示列表里的元素
print('第%d个元素是%d' % (i, num))
Advanced case
[Python] Python realizes the word guessing game-challenge your intelligence and luck!
[python] Python tkinter library implements GUI program for weight unit converter
[python] Use Selenium to get (2023 Blog Star) entries
Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition
[Xiaobai must see] Python word cloud generator detailed analysis and code implementation
[Xiaobai must see] Python crawls an example of NBA player data
[Must-see for Xiaobai] Sample code for crawling and saving Himalayan audio using Python
[Xiaobai must see] Python crawler data processing and visualization
[Must-see for Xiaobai] Python crawler program to easily obtain hero skin pictures of King of Glory
[Must-see for Xiaobai] Use Python to generate a personalized list Word document
Geospatial data processing and visualization using geopandas and shapely (.shp)
Use selenium to crawl Maoyan movie list data
Detailed explanation of the principle and implementation of image enhancement algorithm Retinex
Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis
Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API
Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies
Getting started with crawlers (2): How to use regular expressions for data extraction and processing
Getting started with reptiles (1): Learn the basics and skills of reptiles
Python object-oriented programming basics and sample code
MySQL database operation guide: learn how to use Python to add, delete, modify and query operations
Python file operation guide: encoding, reading, writing and exception handling
Selenium Automation Toolset - Complete Guide and Tutorials
Python web crawler basics advanced to actual combat tutorial
Pandas data processing and analysis tutorial: from basics to actual combat
Detailed explanation of commonly used data types and related operations in Python
[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model