1、去空格及特殊符号
s.strip() s.lstrip() s.rstrip() s.strip().lstrip().rstrip()
声明:s为字符串,rm为要删除的字符序列
s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符
2、复制字符串
#strcpy(str1,str2)str1 = 'strcpy'str2 = str1 str1 = 'strcpy2'print str2
3、连接字符串
#strcat(str1,str2)str1 = 'strcat'str2 = 'append'str1 += str2print str1
4、查找字符
#strchr(str1,str2)# <p></p><p> </p><p><strong>5、比较字符串</strong></p><p class="cnblogs_code"></p><pre class="brush:php;toolbar:false">#strcmp(str1,str2)str1 = 'strchr'str2 = 'strch'print cmp(str1,str2)
6、扫描字符串是否包含指定的字符
#strspn(str1,str2)str1 = '12345678'str2 = '456'#str1 and chars both in str1 and str2print len(str1 and str2)
7、字符串长度
#strlen(str1)str1 = 'strlen'print len(str1)
8、将字符串中的大小写转换
S.lower() #小写 S.upper() #大写 S.swapcase() #大小写互换 S.capitalize() #首字母大写 String.capwords(S) #这是模块中的方法。它把S用split()函数分开,然后用capitalize()把首字母变成大写,最后用join()合并到一起 #实例:#strlwr(sStr1)str1 = 'JCstrlwr'str1 = str1.upper()#str1 = str1.lower()print str1
9、追加指定长度的字符串
#strncat(str1,str2,n)str1 = '12345'str2 = 'abcdef'n = 3str1 += str2[0:n]print str1
10、字符串指定长度比较
#strncmp(str1,str2,n)str1 = '12345'str2 = '123bc'n = 3print cmp(str1[0:n],str2[0:n])
11、复制指定长度的字符
#strncpy(str1,str2,n)str1 = ''str2 = '12345'n = 3str1 = str2[0:n]print str1
12、将字符串前n个字符替换为指定的字符
str1 = '12345'ch = 'r'n = 3str1 = n * ch + str1[3:]print str1
13、扫描字符串
#strpbrk(str1,str2)str1 = 'cekjgdklab'str2 = 'gka'nPos = -1for c in str1: if c in str2: nPos = str1.index(c) breakprint nPos
14、翻转字符串
#strrev(str1)str1 = 'abcdefg'str1 = str1[::-1]print str1
15、查找字符串
#strstr(str1,str2)str1 = 'abcdefg'str2 = 'cde'print str1.find(str2)
16、分割字符串
#strtok(str1,str2)str1 = 'ab,cde,fgh,ijk'str2 = ','str1 = str1[str1.find(str2) + 1:]print str1#或者s = 'ab,cde,fgh,ijk'print(s.split(','))
17、连接字符串
delimiter = ','mylist = ['Brazil', 'Russia', 'India', 'China']print delimiter.join(mylist)
18、PHP 中 addslashes 的实现
def addslashes(s): d = {'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"} return ''.join(d.get(c, c) for c in s) s = "John 'Johny' Doe (a.k.a. \"Super Joe\")\\\0"print sprint addslashes(s)
19、只显示字母与数字
def OnlyCharNum(s,oth=''): s2 = s.lower(); fomart = 'abcdefghijklmnopqrstuvwxyz0123456789' for c in s2: if not c in fomart: s = s.replace(c,''); return s;print(OnlyStr("a000 aa-b"))
20、截取字符串
str = '0123456789' str[0:3] str[:] str[6:] str[:-3] str[2] str[-1] str[::-1] str[-3:-1] str[-3:] str[:-5:-3]
21、字符串在输出时的对齐
S.ljust(width,[fillchar]) #输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。 S.rjust(width,[fillchar]) #右对齐 S.center(width, [fillchar]) #中间对齐 S.zfill(width) #把S变成width长,并在右对齐,不足部分用0补足
22、字符串中的搜索和替换
S.find(substr, [start, [end]]) #返回S中出现substr的第一个字母的标号,如果S中没有substr则返回-1。start和end作用就相当于在S[start:end]中搜索 S.index(substr, [start, [end]]) #与find()相同,只是在S中没有substr时,会返回一个运行时错误 S.rfind(substr, [start, [end]]) #返回S中最后出现的substr的第一个字母的标号,如果S中没有substr则返回-1,也就是说从右边算起的第一次出现的substr的首字母标号 S.rindex(substr, [start, [end]]) S.count(substr, [start, [end]]) #计算substr在S中出现的次数 S.replace(oldstr, newstr, [count]) #把S中的oldstar替换为newstr,count为替换次数。这是替换的通用形式,还有一些函数进行特殊字符的替换 S.strip([chars]) #把S中前后chars中有的字符全部去掉,可以理解为把S前后chars替换为None S.lstrip([chars]) S.rstrip([chars]) S.expandtabs([tabsize]) #把S中的tab字符替换没空格,每个tab替换为tabsize个空格,默认是8个
23、字符串的分割和组合
S.split([sep, [maxsplit]]) #以sep为分隔符,把S分成一个list。maxsplit表示分割的次数。默认的分割符为空白字符 S.rsplit([sep, [maxsplit]]) S.splitlines([keepends]) #把S按照行分割符分为一个list,keepends是一个bool值,如果为真每行后而会保留行分割符。 S.join(seq) #把seq代表的序列──字符串序列,用S连接起来
24、字符串的mapping,这一功能包含两个函数
String.maketrans(from, to) #返回一个256个字符组成的翻译表,其中from中的字符被一一对应地转换成to,所以from和to必须是等长的。 S.translate(table[,deletechars]) # 使用上面的函数产后的翻译表,把S进行翻译,并把deletechars中有的字符删掉。需要注意的是,如果S为unicode字符串,那么就不支持 deletechars参数,可以使用把某个字符翻译为None的方式实现相同的功能。此外还可以使用codecs模块的功能来创建更加功能强大的翻译表。
25、字符串还有一对编码和解码的函数
S.encode([encoding,[errors]]) # 其中encoding可以有多种值,比如gb2312 gbk gb18030 bz2 zlib big5 bzse64等都支持。errors默认值为"strict",意思是UnicodeError。可能的值还有'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 和所有的通过codecs.register_error注册的值。这一部分内容涉及codecs模块,不是特明白 S.decode([encoding,[errors]])
26、字符串的测试、判断函数,这一类函数在string模块中没有,这些函数返回的都是bool值
S.startswith(prefix[,start[,end]]) #是否以prefix开头 S.endswith(suffix[,start[,end]]) #以suffix结尾 S.isalnum() #是否全是字母和数字,并至少有一个字符 S.isalpha() #是否全是字母,并至少有一个字符 S.isdigit() #是否全是数字,并至少有一个字符 S.isspace() #是否全是空白字符,并至少有一个字符 S.islower() #S中的字母是否全是小写 S.isupper() #S中的字母是否便是大写 S.istitle() #S是否是首字母大写的
27、字符串类型转换函数,这几个函数只在string模块中有
string.atoi(s[,base]) #base默认为10,如果为0,那么s就可以是012或0x23这种形式的字符串,如果是16那么s就只能是0x23或0X12这种形式的字符串 string.atol(s[,base]) #转成long string.atof(s[,base]) #转成float
这里再强调一次,字符串对象是不可改变的,也就是说在python创建一个字符串后,你不能把这个字符中的某一部分改变。任何上面的函数改变了字符串后,都会返回一个新的字符串,原字串并没有变。其实这也是有变通的办法的,可以用S=list(S)这个函数把S变为由单个字符为成员的list,这样的话就可以使用S[3]='a'的方式改变值,然后再使用S=" ".join(S)还原成字符串
更多Python 字符串操作相关文章请关注PHP中文网!

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

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

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

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

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

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

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

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

Notepad++7.3.1
Easy-to-use and free code editor

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),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.