Python tutorial: 15 string manipulation methods

Strings are sequences of characters. Strings are basically groups of words. I can pretty much guarantee that you will use strings in every Python program, so please pay special attention to the following sections. Here's how to work with strings in Python.

1. String definition

Using single quotes' You can use single quotes to denote strings, as in 'This is a sentence'.

str = '这是一句话'
print( str )

Using double quotes " Strings enclosed in double quotes are used exactly the same as strings enclosed in single quotes, such as "What's your name?".

str = "What's your name?"
print( str )

Using triple quotes (''' or """) With triple quotes, you can indicate a multi-line string. You can freely use single quotes and double quotes within triple quotes.

str ='''
这是一个多行文本. 这是第一行.这是第二行.
"你的名字是," 我问到。他会答"我的名字是木木"
'''
print(str)

The escape character assumes you want to include a single quote (') in a string, so how do you indicate this string?

For example, this string is What's your name?.

You certainly wouldn't indicate it with 'What's your name?', because Python would have no idea where the string starts and ends. So, you need to indicate the single quote instead of the end of the string. This task can be accomplished through escape characters.

You use ' to indicate a single quote - note the backslash. Now you can represent the string as 'What's your name?'.

Another way to represent this particular string is "What's your name?", using double quotes

str1 = 'What\'s your name?'
str2 = "What's your name?"
print(str1)
print(str2)

2. Index (ie subscript)

s = 'ABCDEFGHIJKLMN'
s1 = s[0]
print('s[0] = ' + s1)   #s[0] = A
print('s[3] = '+ s[3])  #s[3] = D
print('倒数第三个数为:' + s[-3])   #倒数第三个数为:L
print('最后一个数为:' + s[-1])     #最后一个数为:N

3. Slicing: regardless of the beginning and the end (intercept a part of the string)

s = 'ABCDEFGHIJKLMN'
s2 = s[0:3]
print('s[0:3] = ' + s2)     
#s[0:3] = ABCprint('整个字符串如下:' + s[:])    
#整个字符串如下:ABCDEFGHIJKLMNprint('整个字符串如下:' + s[0:])   
#整个字符串如下:ABCDEFGHIJKLMNprint('前两个字符:' + s[:2])      
 #前两个字符:AB

4. Jump to s[first: tail: step size]

s3 = 'ABCDEFGHIJKLMN'
print(s3[0:6:2])    #ACE
print(s3[::2])      #ACEGIKM
print(s3[4:0:-1])   #倒着取:EDCB
print(s3[3::-1])    #DCBA
print(s3[-1::-1])   #NMLKJIHGFEDCBA

5. String operations

1) Capitalize the first letter

s = 'alexWUsir'
s4_1 = s.capitalize()  #首字母大写
print(s4_1)   #Alexwusir

2) All caps

s = 'alexWUsir'
s4_2 = s.upper() #全部大写
print(s4_2)   #ALEXWUSIR

3) All lowercase

s = 'alexWUsir'
s4_3 = s.lower() #全部小写
print(s4_3)   #alexwusir

4) Swap case

s = 'alexWUsir'
s4_4 = s.swapcase() #大小写互换
print(s4_4)   #ALEXwuSIR

6. Center (fill with whitespace/other characters)

#center(self, width, fillchar=None)s = 'alexWUsir'
s5_1 = s.center(20,'%')  #用%填充
s5_2 = s.center(15,'*')  #用*填充
s5_3 = s.center(20)      #空白填充
print(s5_1)     #%%%%%alexWUsir%%%%%%
print(s5_2) 
  #***alexWUsir***
print(s5_3)   #     alexWUsir

7. Capitalize the first letter of each word separated by special characters or numbers

s = 'xc——gx*zs_shy+hihn9bbklv yiu'
s7 = s.title()
print(s7)  
#Xc——Gx*Zs_Shy+Hihn9Bbklv Yiu

Applications:

print('------------验证码的检验问题(先转化为全部大写,再核对) --------------')
s_str = 'aBcD1s'
you_input = input('请输入验证码,不区分大小写')
while s_str.upper()!= you_input.upper():
    print('验证码错误')
    you_input = input('请重新输入')
print('输入成功')

8. Find

s.find finds the index through the element, finds the return index, and returns -1 if not found
s.index finds the index through the element, finds the return index, and returns error if not found

s = 'alexWUsir'
s8_11 = s.find('W')
s8_12 = s.index('W')
s8_21 = s.find('WU')
s8_22 = s.index('WU')
s8_31 = s.find('A')
s8_32 = s.index('A')
print(s8_11,type(s8_12))     
 #4 <class 'int'>print(s8_21 ,type(s8_22))    
 #4 <class 'int'>print(s8_31 ,type(s8_32))     
#报错:ValueError: substring not found----未找到子字符串

Applications:

print('----------------检验非法(敏感)字符-------------------')
s = 'gcu木木gckhb'
if '木木' in s:
    print('您的评论有敏感字符')

9. Remove spaces/characters before and after a string

s = '  alexW%Usir  %2%  '
s9_1 = s.strip()   
#删除字符串前后的空格print(s9_1)   
#alexW%Usir  %2%
​
ss = '% alexW%Usir  %2%  %'
s9_2 = ss.strip('%')   
#删除字符串前后的%print(s9_2)  
# alexW%Usir  %2%  

Application examples:

username = input('请输入名字:').strip()
if username == '小明':
    print('你好呀 主人')

10. Count the number of characters/strings in a string

s = 'alexaa wusirl'
s10 = s.count('a')
print('此字符串中有' + s10 + '个a')   
#报错:TypeError: must be str, not intprint('此字符串中有' + str(s10) + '个a')    
#此字符串中有3个a

11. Split: Split the string with spaces (default)/fixed characters (equivalent to str—>list)

s = 'alex wusir taibai'
s1 = 'ale:x wus:ir :taibai'
s11_1 = s.split()
print(s11_1)    #['alex', 'wusir', 'taibai']
s11_2 = s1.split(':')print(s11_2)   #['ale', 'x wus', 'ir ', 'taibai']

12. Three formatted output formats

s12_1 = '我叫{},今年{}岁,爱好{},再说一下我叫{}'.format('小明',18,'学习','小明')
print(s12_1)   



s12_2 = '我叫{0},今年{1}岁,爱好{2},再说一下我叫{0}'.format('小明',18,'学习')

print(s12_2)
​

s12_3 = s1 = '我叫{name},今年{age}岁,爱好{hobby},再说一下我叫{name}'.format(name = '小明',age = 18,hobby = '学习')

print(s12_3)

13. replace String replacement

s13_1 = '小明,哈喽你好,我是小明'
s13_2 = s13_1.replace('小明','张三')
s13_3 = s13_1.replace('小明','张三',1)print(s13_1)

print(s13_2)

print(s13_3)

14. is series

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
s14 = ''print(s14.isdigit())   #是否由数字组成
print(s14.isalpha())   #是否由字母组成
print(s14.isalnum())   #是否由字母或数字组成
s14_1 = 'zxcs'
s14_2 = '123546'
s14_3 = 'c1d21c4'
print('----------s14_1----------')
print(s14_1.isdigit())   #False
print(s14_1.isalpha())   #True
print(s14_1.isalnum())   #True
print('----------s14_2----------')
print(s14_2.isdigit())  #True
print(s14_2.isalpha())   #False
print(s14_2.isalnum())   #True
print('----------s14_3----------')
print(s14_3.isdigit())   #False
print(s14_3.isalpha())   #False
print(s14_3.isalnum())   #True

Check if a string is full of spaces

s14_4 = ' n  '
s14_5 = ''
s14_6 = '   '
print(s14_4.isspace())  #False:有除空格外的其他字符
print(s14_5.isspace())  #False:空
print(s14_6.isspace())  #True:全是空格

15. Finite loop for (while is an infinite loop)

s = 'xiaoming'
for i in s:
    print(i)

#举例:

s = 'fhdsklfds'
if 'sk' in s:
    print('非法')
print('------------------------')
if 'skk' not in s:
    print('合法')

Guess you like

Origin blog.csdn.net/qdPython/article/details/124063345