search
HomeBackend DevelopmentPython TutorialSharing of string processing skills in Python

这篇文章给大家分享了Python中字符串的处理技巧,包括拆分含有多种分隔符的字符串、判断字符串a是否以字符串b开头或结尾、调整字符串中文本的格式已经将多个小字符串拼接成一个大的字符串等,感兴趣的朋友们可以通过阅读下文来学习。

一、如何拆分含有多种分隔符的字符串?

实际案例

我们要把某个字符串依据分隔符号拆分不同的字符段,该字符串包含多种不同的分隔符,例如:

s = 'asd;aad|dasd|dasd,sdasd|asd,,Adas|sdasd;Asdasd,d|asd'

其中,,,都是分隔符,如何处理?

解决方案

连续使用split()方法,每次处理一种分隔符

# 使用Python2 def mySplit(s,ds): res = [s] for d in ds: t = [] map(lambda x: t.extend(x.split(d)), res) res = t return [x for x in res if x] s = 'asd;aad|dasd|dasd,sdasd|asd,,Adas|sdasd;Asdasd,d|asd' result = mySplit(s, ';,|\t') print(result)

C:\Users\Administrator>C:\Python\Python27\python.exe E:\python-intensive-training\s2.py ['asd', 'aad', 'dasd', 'dasd', 'sdasd', 'asd', 'Adas', 'sdasd', 'Asdasd', 'd', 'asd']

使用正则表达式的re.split()方法,一次性拆分字符串

>>> import re >>> re.split('[,;\t|]+','asd;aad|dasd|dasd,sdasd|asd,,Adas|sdasd;Asdasd,d|asd') ['asd', 'aad', 'dasd', 'dasd', 'sdasd', 'asd', 'Adas', 'sdasd', 'Asdasd', 'd', 'asd']

二、如何判断字符串a是否以字符串b开头或结尾?

实际案例

如某目录有如下文件:

quicksort.c graph.py heap.java install.sh stack.cpp ......

现在需要给.sh.py结尾的文件夹上可执行权限

解决方案

使用字符串的startswith()endswith()方法

>>> import os, stat >>> os.listdir('./') ['heap.java', 'quicksort.c', 'stack.cpp', 'install.sh', 'graph.py'] >>> [name for name in os.listdir('./') if name.endswith(('.sh','.py'))] ['install.sh', 'graph.py'] >>> os.chmod('install.sh', os.stat('install.sh').st_mode | stat.S_IXUSR)

[root@iZ28i253je0Z t]# ls -l install.sh -rwxr--r-- 1 root root 0 Sep 15 18:13 install.sh

三、如何调整字符串中文本的格式?

实际案例

某软件的日志文件,其中日期格式为yyy-mm-dd:

2016-09-15 18:27:26 statu unpacked python3-pip:all 2016-09-15 19:27:26 statu half-configured python3-pip:all 2016-09-15 20:27:26 statu installd python3-pip:all 2016-09-15 21:27:26 configure asdasdasdas:all python3-pip:all

需要把其中日期改为美国日期的格式mm/dd/yyy, 2016-09-15 --> 09/15/2016,要如何处理?

解决方案

使用正则表达式re.sub()方法做字符串替换

利用正则表达式的捕获组,捕获每个部分内容,在替换字符串中各个捕获组的顺序。

>>> log = &#39;2016-09-15 18:27:26 statu unpacked python3-pip:all&#39; >>> import re # 按顺序 >>> re.sub(&#39;(\d{4})-(\d{2})-(\d{2})&#39;, r&#39;\2/\3/\1&#39; , log) &#39;09/15/2016 18:27:26 statu unpacked python3-pip:all&#39; # 使用正则表达式的分组 >>> re.sub(&#39;(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})&#39;, r&#39;\g<month>/\g<day>/\g<year>&#39; , log) &#39;09/15/2016 18:27:26 statu unpacked python3-pip:all&#39;

四、如何将多个小字符串拼接成一个大的字符串?

实际案例

在设计某网络程序时,我们自定义了一个基于UDP的网络协议,按照固定次序向服务器传递一系列参数:

hwDetect: "<0112>" gxDepthBits: "<32>" gxResolution: "<1024x768>" gxRefresh: "<60>" fullAlpha: "<1>" lodDist: "<100.0>" DistCull: "<500.0>"

在程序中我们将各个参数按次序收集到列表中:

["<0112>","<32>","<1024x768>","<60>","<1>","<100.0>","<500.0>"]

最终我们要把各个参数拼接成一个数据包进行发送:

"<0112><32><1024x768><60><1><100.0><500.0>"

解决方案

迭代列表,连续使用'+'操作依次拼接每一个字符串

>>> for n in ["<0112>","<32>","<1024x768>","<60>","<1>","<100.0>","<500.0>"]: ... result += n ... >>> result '<0112><32><1024x768><60><1><100.0><500.0>'

使用str.join()方法,更加快速的拼接列表中所有字符串

>>> result = ''.join(["<0112>","<32>","<1024x768>","<60>","<1>","<100.0>","<500.0>"]) >>> result '<0112><32><1024x768><60><1><100.0><500.0>'

如果列表中有数字,可以使用生成器进行转换:

>>> hello = [222,&#39;sd&#39;,232,&#39;2e&#39;,0.2] >>> &#39;&#39;.join(str(x) for x in hello) &#39;222sd2322e0.2&#39;

五、如何对字符串进行左, 右, 居中对齐?

实际案例

某个字典中存储了一系列属性值:

{ &#39;ip&#39;:&#39;127.0.0.1&#39;, &#39;blog&#39;: &#39;www.anshengme.com&#39;, &#39;title&#39;: &#39;Hello world&#39;, &#39;port&#39;: &#39;80&#39; }

在程序中,我们想以以下格式将其内容输出,如何处理?

ip : 127.0.0.1 blog : www.anshengme.com title : Hello world port : 80

解决方案

使用字符串的str.ljust() , str.rjust,str.cente()进行左右居中对齐

>>> info = {&#39;ip&#39;:&#39;127.0.0.1&#39;,&#39;blog&#39;: &#39;www.anshengme.com&#39;,&#39;title&#39;: &#39;Hello world&#39;,&#39;port&#39;: &#39;80&#39;} # 获取字典中的keys最大长度 >>> max(map(len, info.keys())) 5 >>> w = max(map(len, info.keys())) >>> for k in info: ... print(k.ljust(w), &#39;:&#39;,info[k]) ... # 获取到的结果 port : 80 blog : www.anshengme.com ip : 127.0.0.1 title : Hello world

使用format()方法,传递类似'20','^20'参数完成同样任务

>>> for k in info: ... print(format(k,&#39;^&#39;+str(w)), &#39;:&#39;,info[k]) ... port : 80 blog : www.anshengme.com ip : 127.0.0.1 title : Hello world

六、如何去掉字符串中不需要的字符?

实际案例

过滤掉用户输入卡后多余的空白字符: anshengm.com@gmail.com

过滤某windows下编辑文本中的'\r': hello word\r\n

去掉文本中的unicode组合符号(音调): ‘ní hǎo, chī fàn'

解决方案

字符串strip() , lstrip(),rstrip()方法去掉字符串两端字符

>>> email = &#39; anshengm.com@gmail.com &#39; >>> email.strip() &#39;anshengm.com@gmail.com&#39; >>> email.lstrip() &#39;anshengm.com@gmail.com &#39; >>> email.rstrip() &#39; anshengm.com@gmail.com&#39; >>>

删除某个固定位置的字符,可以使用切片+拼接的方法

>>> s[:3] + s[4:] &#39;abc123&#39;

字符串的replace()方法或正则表达式re.sub()删除任意位置字符

>>> s = &#39;\tabc\t123\txyz&#39; >>> s.replace(&#39;\t&#39;, &#39;&#39;) &#39;abc123xyz&#39;

使用re.sub()删除多个

>>> import re >>> re.sub(&#39;[\t\r]&#39;,&#39;&#39;, string) &#39;abc123xyzopq&#39;

字符串translate()方法,可以同时删除多种不同字符

>>> import string >>> s = &#39;abc123xyz&#39; >>> s.translate(string.maketrans(&#39;abcxyz&#39;,&#39;xyzabc&#39;)) &#39;xyz123abc&#39;

>>> s = &#39;\rasd\t23\bAds&#39; >>> s.translate(None, &#39;\r\t\b&#39;) &#39;asd23Ads&#39;

# python2.7 >>> i = u&#39;ní hǎo, chī fàn&#39; >>> i u&#39;ni\u0301 ha\u030co, chi\u0304 fa\u0300n&#39; >>> i.translate(dict.fromkeys([0x0301, 0x030c, 0x0304, 0x0300])) u&#39;ni hao, chi fan&#39;

总结

以上就是为大家整理的Python中字符串的处理技巧,文中通过案例、解决方案以及实例来演示如何解决,对大家学习或者使用python具有一定的参考借鉴价值。有需要的可以参考借鉴。

更多Python中字符串的处理技巧分享相关文章请关注PHP中文网!


Statement
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
How to Use Python to Find the Zipf Distribution of a Text FileHow to Use Python to Find the Zipf Distribution of a Text FileMar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Mathematical Modules in Python: StatisticsMathematical Modules in Python: StatisticsMar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

Serialization and Deserialization of Python Objects: Part 1Serialization and Deserialization of Python Objects: Part 1Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

What are some popular Python libraries and their uses?What are some popular Python libraries and their uses?Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

Scraping Webpages in Python With Beautiful Soup: Search and DOM ModificationScraping Webpages in Python With Beautiful Soup: Search and DOM ModificationMar 08, 2025 am 10:36 AM

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

How to Create Command-Line Interfaces (CLIs) with Python?How to Create Command-Line Interfaces (CLIs) with Python?Mar 10, 2025 pm 06:48 PM

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.