[Learn python from zero] 24. String manipulation and traversal methods in Python

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

[python] Use Selenium and Chrome WebDriver to obtain article information in [Tencent Cloud Studio Practical Training Camp]

Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition

[Fun with Python series [Xiaobai must see] Python multi-threaded crawler: download pictures of emoticon package websites

[Play with Python series] [Must-see for Xiaobai] Use Python to crawl historical data of Shuangseqiu and analyze it visually

[Play with python series] [Must-see for Xiaobai] Use Python crawler technology to obtain proxy IP and save it to a file

[Must-see for Xiaobai] Python image synthesis example using PIL library to realize the synthesis of multiple images by ranks and columns

[Xiaobai must see] Python crawler actual combat downloads pictures of goddesses in batches and saves them locally

[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

[Must-see for Xiaobai] Technical realization of using Python to download League of Legends skin pictures in batches

[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

[Must-see for Xiaobai] Python crawler combat: get pictures from Onmyoji website and save them automatically

Xiaobai must-see series of library management system - sample code for login and registration functions

100 Cases of Xiaobai's Actual Combat: A Complete and Simple Shuangseqiu Lottery Winning Judgment Program, Suitable for Xiaobai Getting Started

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

Introductory Guide to Crawlers (7): Using Selenium and BeautifulSoup to Crawl Douban Movie Top250 Example Explanation [Reptile Xiaobai must watch]

Getting Started Guide to Crawlers (6): Anti-crawlers and advanced skills: IP proxy, User-Agent disguise, Cookie bypass login verification and verification code identification tools

Introductory Guide to Crawlers (5): Distributed Crawlers and Concurrency Control [Implementation methods to improve crawling efficiency and request rationality control]

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

Application of Deep Learning Model in Image Recognition: CIFAR-10 Dataset Practice and Accuracy Analysis

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

Use Python and Selenium to automate crawling#【Dragon Boat Festival Special Call for Papers】Explore the ultimate technology, and the future will be due to you"Zong" #Contributed articles

Python multi-thread and multi-process tutorial: comprehensive analysis, code cases and optimization skills

Selenium Automation Toolset - Complete Guide and Tutorials

Python web crawler basics advanced to actual combat tutorial

Python introductory tutorial: master the basic knowledge of for loop, while loop, string operation, file reading and writing and exception handling

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

Introductory Python programming basics and advanced skills, web development, data analysis, and machine learning and artificial intelligence

Graph prediction results with 4 regression methods: Vector Regression, Random Forest Regression, Linear Regression, K-Nearest Neighbors Regression

Guess you like

Origin blog.csdn.net/qq_33681891/article/details/132290277