Common operations of Python strings

Note: String is an immutable data type, any operation on the string will not change the original string ! !

1. Subscript and slice of string:

1. Subscripts are also called indexes. In python, strings, lists, and tuples can be used to obtain or manipulate data through subscripts;
2. Note: Strings and tuples cannot be used to change the original data through subscripts ;
3. The subscripts all start from 0, 0 represents the subscript of the first element, -1 represents the subscript of the last element, -2 is the subscript of the penultimate, and so on;

word='hello world'
print(word[4])# 'o'
print(word[0])# 'h'
print(word[-1])# 'd'
# word[4]='x' TypeError: 'str' object does not support item assignment

4. Slicing is to copy a specified content from a string to generate a new string
(1) The slicing syntax: m[start:END:step], m is the string variable name, start is the starting subscript, END It is the end subscript, including start but not END;
(2) start and END can also be omitted, but the colon in the middle cannot be omitted
(3) step is the step size, the default is 1, which can be understood as an interval, without a |step| -1 takes one, the step length cannot be 0. When the step is a positive number, it is from left to right, otherwise it is from right to left;
(4) When step is omitted, the preceding colon can also be omitted. It is generally used to perform string Reverse, that is, step takes -1;
(5) The slices of lists and tuples are the same as above;

word='hello world'
print(word[::-1]) # 'dlrow olleh'
print(word[2:]) # 'llo world'
print(word[:9]) # 'hello wor'
print(word[::2])# 'hlowrd'
print(word[-10:5])# 'ello'

Two, get the string length

You can use the len() function to get the length of strings, lists, and tuples.

word='hello world'
print(len(word))# 11

Three, find related methods

1. Find related methods: find/index/rfind/rindex;
2. Both find and index methods start from the left and return the first matching subscript, while rfind and rindex start from the right and return to the first A matching subscript;
3. If find and rfind do not match, it will return -1, and if index and rindex do not match, an error will be reported;

print(x.find('n')) # 4
print(x.find('p')) # -1
print(x.index('n')) # 4
print(x.rfind('p')) # -1
print(x.rindex('n')) # 15
# print(x.index('p')) # ValueError: substring not found

Fourth, judgments related to strings

startswith: judge whether a string starts with a character or a string;
endswith: judge whether a string ends with a character or a string;
isalpha: judge whether the string consists of all letters;
isdigit: judge whether the string is all It is composed of numbers;
isalnum: judges whether the string is composed of numbers or characters;
isspace: judges whether the string is composed of all spaces;
isupper: judges whether the string is composed of all uppercase letters;
islower: judges whether the string is composed of all lowercase letters ;
The following is an example that separates numbers and letters:
strings can also be traversed

word = '1aaa2bbb13c4 d5cd6d7e8f9g'
al_word = '' # 创建一个等下用来保存字母的空字符串
di_word = '' # 创建一个等下用来保存数字的空字符串
for i in word:
    if i.isalpha(): 
        al_word += i # 字符串拼接
    elif i.isdigit():
        di_word += i
    elif i.isspace(): # 遇到空格我们就停止
        break
print(al_word) # 'aaabbbc'
print(di_word) # '12134'

Five, count() method

count: Returns the number of times a character appears in the entire string, and the list tuple is used for the same;

word = 'hello hi hei he'
print(word.count('h')) # 4
l = ['a','b','a',1,2,3,1,2,1]
print(l.count(1)) # 3

Six, the content of the string split split join

Split: Split the string by a certain character and split it into a list. The default is to split by spaces. If you specify the number of times, the split will not exceed count times, and rsplit will split from the right;

m = 'zhangsan lisi wangwu maliu'
n = m.split()
print(n) # ['zhangsan', 'lisi', 'wangwu', 'maliu']
x = 'zhangsan-lisi-wangwu-maliu'
a = x.split('-', 5)  # 从左边开始找分割符进行分割
b = x.rsplit('-', 1)  # 从右边开始找分割符进行分割
print(a) # ['zhangsan', 'lisi', 'wangwu', 'maliu']
print(b) # ['zhangsan-lisi-wangwu', 'maliu']

If you can split it, you can join together. You can use the join method. Join is also a method of string. It can use the string given above to join list tuple dictionary (only key value) collection, etc., but the content to be joined must be characters String, for example, to concatenate lists, the elements in the list must be strings

num =['123','456','789','000']
print(''.join(num))# '123456789000' join括号里是可迭代对象
print('+'.join(('我爱你','enna'))) # 我爱你+enna

partition: Divide a specified string into three parts: after the previous separator, a tuple is returned;

c = 'abcdefghigjklmn'
d = c.partition('g') # 从左边开始找分割符进行分割
e = c.rpartition('g') # 从右边开始找分割符进行分割
print(d) # ('abcdef', 'g', 'higjklmn')
print(e) # ('abcdefghi', 'g', 'jklmn')

The words in the string are letter blocks separated by any punctuation marks or numbers

# capitalize 让第一个单词的首字母大写,其他小写
print('hello world.GOOD'.capitalize())# Hello world.good
# upper 全大写
print('hello'.upper()) # HELLO
# lower全小写
print('HEL22LO'.lower()) # hel22lo
# title 每个单词的首字母大写,其他小写
print('he1ll2o worldGOOD'.title()) # He1Ll2O Worldgood
# swapcase 大小写反转
print('HelloWORLD'.swapcase())# hELLOworld

Hope these help you a bit

I cheated and praised QAQ again

Guess you like

Origin blog.csdn.net/hmh4640219/article/details/112599464