Common methods of python string
- 2021-12-11 18:08:17
- OfStack
1. find (sub [, start [, end]])
In the index
start
And
end
Look up strings between
sub
If found, the leftmost index value is returned; If not found, the index value is returned
-1
start
And
end
Can be omitted, omitted
start
Explain finding from the beginning of a string
Omission
end
Explain that the end of the string is found, and all strings are found if all are omitted
source_str = "There is a string accessing example"
print(source_str.find('r'))
>>> 3
2. count (sub, start, end)
Return string
sub
In
start
And
end
Number of occurrences between
source_str = "There is a string accessing example"
print(source_str.count('e'))
>>> 5
3. replace (old, new, count)
old
Represents the character to be replaced,
new
Represents the character to be replaced,
count
Represents the number of replacements (omission means all replacements)
source_str = "There is a string accessing example"
print(source_str.replace('i', 'I', 1))
>>> There Is a string accessing example # Put lowercase i Replaced with capitalized I
4. split (sep, maxsplit)
With
sep
Is a delimiter slice, if
maxsplit
If there is a specified value, only the partition
maxsplit
String
After segmentation, the original str type will be converted to
list
Type
source_str = "There is a string accessing example"
print(source_str.split(' ', 3))
>>> ['There', 'is', 'a', 'string accessing example'] # Here you specify maxsplit=3 Represents only before division 3 A
5. startswith (prefix, start, end)
Determines whether the string is based on the
prefix
At the beginning,
start
And
end
Represents which subscript begins and which subscript ends
source_str = "There is a string accessing example"
print(source_str.startswith('There', 0, 9))
>>> True
6. endswith (suffix, start, end)
Determines whether the string is used with
sub
1
End, if it is returned
True
Otherwise, return
False
source_str = "There is a string accessing example"
print(source_str.endswith('example'))
>>> True
7. lower
Convert all uppercase characters to lowercase
8. upper
Converts all lowercase characters to uppercase
9. join
Splice a list into a string
list1 = ['ab', 'cd', 'ef']
print(" ".join(list1))
>>> ab cd ef
10. Slice inversion
list2 = "hello"
print(list2[::-1])
>>> olleh