Common methods of operation string python

Common methods of operation string python

First emphasize: an immutable string data type, that is to say after the python created a string, you can not put a certain part of the string change, any change in the above function string,
returns a new string , the source string has not changed.

Python string following summary for common operations, such as the replacement string, delete, slices taken, replication, connection, comparison, search, segmentation, and list conversion, inversion, sorting ,, judgment.

1, replacing str.replace (str1, str2, num) replaced with str2 out str1 num is the number of default from left to right

str_1 = "Welcome to python ha ha"
str_2 = str_1.replace('ha', 'Hi', 1).replace('to', 'using')
print(str_2)  
>>>"Welcome using python Hi ha"
print(str_1)
>>>"Welcome to python ha ha"  #  原字符串的值不变  字符串属于不可变类型数据

2, delete

str.strip (str1) to delete the specified character string on both sides, writes the specified character brackets, the default is a space
str.lstrip (str1) to delete from the left side of the string specified character
str.rstrip (str2) delete the specified string to the right characters, the default space

str_1 = '  hello  '
str_2 = str_1.strip()
print(str_2) 
>>> 'hello'

str_3 = str_1.lstrip()
print(str_3) 
>>>'  hello'

3, slice taken str [::]

4. Copy

Str_l = 'Mjy'
Str_2 = Str_l
print (Str_2)

Mjy

5, is connected +

str_1 = 'hello'
str_2 = 'girl'
str_3 = str_1 +str2
print(str_3)

'hello girl'

6, comparison cmp (X, Y)

This method has no python3

Comparison of two objects, based on the results and returns an integer. X <Y, the return value is negative, X> Y returns a positive number for
`` `python

python2

cmd(2, 1)

1
cmd(1, 2)
-1

python3 no cmd () method, with only> and <comparing (string comparison may be)

cmd(2, 1)

"name 'cmd' is not defined"

7. Find

str.find () str.index same () function, except that the find () will return -1 lookup fails, does not affect the operation of the program. General use find = -! 1 or find> -1 as the determination condition.
str.index: detecting whether a string contains the substring str, can be specified range, will fail to find an error
in addition str.rfind (str1, start, end) /str.rindex () from the end to start looking

str_1 = 'hello world'
str_1.index('l')
>>>2

#str.find:检测字符串中是否包含子字符串str,可指定范围
str_1 = 'hello world'
str_1.find('l')
>>>2
str_1.find('x')
>>>-1

8, divided

str.split (str1) dividing the string specified default string substring The space dividing, the result is a list of

str_1 = 'hello, girl'
res = str_1.split(',')
print(res)     # 结果是列表
>>>['hello', 'girl']

9, and a list of conversion

```python

The elements in the list to the specified character string connected

res = ['hello', 'girl']
str_1 = ('@').jion(res)
print(str_1)

Results string 'hello @ girl' # spliced

str_2 = (',').join(res)
print(str_2)

'hello,girl'

Guess you like

Origin www.cnblogs.com/We612/p/11117912.html