Home Backend Development Python Tutorial A complete collection of Python string manipulation methods

A complete collection of Python string manipulation methods

Jan 13, 2017 pm 04:30 PM

1、去空格及特殊符号

s.strip().lstrip().rstrip(',')
Copy after login

2、复制字符串

#strcpy(sStr1,sStr2)
sStr1 = 'strcpy'
sStr2 = sStr1
sStr1 = 'strcpy2'
print sStr2
Copy after login

3、连接字符串

#strcat(sStr1,sStr2)
sStr1 = 'strcat'
sStr2 = 'append'
sStr1 += sStr2
print sStr1
Copy after login

4、查找字符

#strchr(sStr1,sStr2)
# < 0 为未找到
sStr1 = &#39;strchr&#39;
sStr2 = &#39;s&#39;
nPos = sStr1.index(sStr2)
print nPos
Copy after login

5、比较字符串

#strcmp(sStr1,sStr2)
sStr1 = &#39;strchr&#39;
sStr2 = &#39;strch&#39;
print cmp(sStr1,sStr2)
Copy after login

6、扫描字符串是否包含指定的字符

#strspn(sStr1,sStr2)
sStr1 = &#39;12345678&#39;
sStr2 = &#39;456&#39;
#sStr1 and chars both in sStr1 and sStr2
print len(sStr1 and sStr2)
Copy after login

7、字符串长度

#strlen(sStr1)
sStr1 = &#39;strlen&#39;
print len(sStr1)
Copy after login

8、将字符串中的大小写转换

S.lower() #小写 
S.upper() #大写 
S.swapcase() #大小写互换 
S.capitalize() #首字母大写 
String.capwords(S) #这是模块中的方法。它把S用split()函数分开,然后用capitalize()把首字母变成大写,最后用join()合并到一起 
#实例:
#strlwr(sStr1)
sStr1 = &#39;JCstrlwr&#39;
sStr1 = sStr1.upper()
#sStr1 = sStr1.lower()
print sStr1
Copy after login

9、追加指定长度的字符串

#strncat(sStr1,sStr2,n)
sStr1 = &#39;12345&#39;
sStr2 = &#39;abcdef&#39;
n = 3
sStr1 += sStr2[0:n]
print sStr1
Copy after login

10、字符串指定长度比较

#strncmp(sStr1,sStr2,n)
sStr1 = &#39;12345&#39;
sStr2 = &#39;123bc&#39;
n = 3
print cmp(sStr1[0:n],sStr2[0:n])
Copy after login

11、复制指定长度的字符

#strncpy(sStr1,sStr2,n)
sStr1 = &#39;&#39;
sStr2 = &#39;12345&#39;
n = 3
sStr1 = sStr2[0:n]
print sStr1
Copy after login

12、将字符串前n个字符替换为指定的字符

#strnset(sStr1,ch,n)
sStr1 = &#39;12345&#39;
ch = &#39;r&#39;
n = 3
sStr1 = n * ch + sStr1[3:]
print sStr1
Copy after login

13、扫描字符串

#strpbrk(sStr1,sStr2)
sStr1 = &#39;cekjgdklab&#39;
sStr2 = &#39;gka&#39;
nPos = -1
for c in sStr1:
    if c in sStr2:
        nPos = sStr1.index(c)
        break
print nPos
Copy after login

14、翻转字符串

#strrev(sStr1)
sStr1 = &#39;abcdefg&#39;
sStr1 = sStr1[::-1]
print sStr1
Copy after login

15、查找字符串

#strstr(sStr1,sStr2)
sStr1 = &#39;abcdefg&#39;
sStr2 = &#39;cde&#39;
print sStr1.find(sStr2)
Copy after login

16、分割字符串

#strtok(sStr1,sStr2)
sStr1 = &#39;ab,cde,fgh,ijk&#39;
sStr2 = &#39;,&#39;
sStr1 = sStr1[sStr1.find(sStr2) + 1:]
print sStr1
#或者
s = &#39;ab,cde,fgh,ijk&#39;
print(s.split(&#39;,&#39;))
Copy after login

17、连接字符串

delimiter = &#39;,&#39;
mylist = [&#39;Brazil&#39;, &#39;Russia&#39;, &#39;India&#39;, &#39;China&#39;]
print delimiter.join(mylist)
Copy after login

18、PHP 中 addslashes 的实现

def addslashes(s):
    d = {&#39;"&#39;:&#39;\\"&#39;, "&#39;":"\\&#39;", "\0":"\\\0", "\\":"\\\\"}
    return &#39;&#39;.join(d.get(c, c) for c in s)

s = "John &#39;Johny&#39; Doe (a.k.a. \"Super Joe\")\\\0"
print s
print addslashes(s)
Copy after login

19、只显示字母与数字

def OnlyCharNum(s,oth=&#39;&#39;):
    s2 = s.lower();
    fomart = &#39;abcdefghijklmnopqrstuvwxyz0123456789&#39;
    for c in s2:
        if not c in fomart:
            s = s.replace(c,&#39;&#39;);
    return s;

print(OnlyStr("a000 aa-b"))
Copy after login

20、截取字符串

str = &#39;0123456789′
print str[0:3] #截取第一位到第三位的字符
print str[:] #截取字符串的全部字符
print str[6:] #截取第七个字符到结尾
print str[:-3] #截取从头开始到倒数第三个字符之前
print str[2] #截取第三个字符
print str[-1] #截取倒数第一个字符
print str[::-1] #创造一个与原字符串顺序相反的字符串
print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
print str[-3:] #截取倒数第三位到结尾
print str[:-5:-3] #逆序截取,具体啥意思没搞明白?
Copy after login

21、字符串在输出时的对齐

S.ljust(width,[fillchar]) 
#输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。 
S.rjust(width,[fillchar]) #右对齐 
S.center(width, [fillchar]) #中间对齐 
S.zfill(width) #把S变成width长,并在右对齐,不足部分用0补足
Copy after login

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个
Copy after login

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连接起来
Copy after login

24、字符串的mapping,这一功能包含两个函数

String.maketrans(from, to) 
#返回一个256个字符组成的翻译表,其中from中的字符被一一对应地转换成to,所以from和to必须是等长的。 
S.translate(table[,deletechars]) 
# 使用上面的函数产后的翻译表,把S进行翻译,并把deletechars中有的字符删掉。需要注意的是,如果S为unicode字符串,那么就不支持 deletechars参数,可以使用把某个字符翻译为None的方式实现相同的功能。此外还可以使用codecs模块的功能来创建更加功能强大的翻译表。
Copy after login

25、字符串还有一对编码和解码的函数

S.encode([encoding,[errors]]) 
# 其中encoding可以有多种值,比如gb2312 gbk gb18030 bz2 zlib big5 bzse64等都支持。errors默认值为"strict",意思是UnicodeError。可能的值还有&#39;ignore&#39;, &#39;replace&#39;, &#39;xmlcharrefreplace&#39;, &#39;backslashreplace&#39; 和所有的通过codecs.register_error注册的值。这一部分内容涉及codecs模块,不是特明白 
S.decode([encoding,[errors]])
Copy after login

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是否是首字母大写的
Copy after login

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
Copy after login

这里再强调一次,字符串对象是不可改变的,也就是说在python创建一个字符串后,你不能把这个字符中的某一部分改变。任何上面的函数改变了字符串后,都会返回一个新的字符串,原字串并没有变。其实这也是有变通的办法的,可以用S=list(S)这个函数把S变为由单个字符为成员的list,这样的话就可以使用S[3]='a'的方式改变值,然后再使用S=" ".join(S)还原成字符串

更多Python 字符串操作方法大全相关文章请关注PHP中文网!


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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1237
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles