A directory of Python tutorials for skilled programmers

How do I split a string with multiple delimiters

Use the split method in the RE package, which passes in a regular expression and the string to split, returning an array of strings

from re import split
s = 'ab; cd|edfh,iws,a\twsw,as\twqa'
print(split(r'[,;\t|]+', s))
Copy the code

How do I determine whether a string begins or ends with another string

Use the endswith method of strings, which can take a tuple of strings and return True if the string ends in one of the tuples, False otherwise.

from os import listdir
for dir in listdir('. ') :print(dir.dir.endswith(('.idea'.'.py'))) Only tuples can be passed
Copy the code

Print (oct(stat(‘ ch04.py ‘).st_mode))

How to format the text of a string

log = '2010-08-01'
from re import sub
print(sub('(\d{4})-(\d{2})-(\d{2})'.r'\2/\3/\1', log))
Copy the code

# How to concatenate multiple small strings into one large string

s1 = 'abcdefg'
s2 = '12345'

print(s1 + s2)       The addition of two strings essentially calls the __add__ function
print(s1.__add__(s2))

print(s1 > s2)       # Compare two strings, essentially calling the __gt__ function
print(s1.__gt__(s2))
Copy the code

Concatenate a string from a list

print('; '.join(['abc'.'123'.'xyz']))
print(' '.join([str(x) for x in ['abc'.123.'xyz']]))
Copy the code

How do I align strings left, center, and right

s = 'abc'
print(s.ljust(20.'='))
print(s.rjust(20))
Copy the code

Extension: Gets the maximum length of a string in a collection of strings

max(map(len, d.keys()))
Copy the code

How to remove unnecessary characters from a string

s = ' abc 123 '
print(s.strip())  # Remove the Spaces on both sides
print(s.lstrip()) # Remove the left space
s = '---abc+++'
print(s.strip('+' -)) # remove '-' or '+' from both sides

s = 'abc+1-23'
print(s[:3] + s[4:)print(s.replace('+'.' '))

from re import sub

print(sub(r'[+-]'.' ', s)) # remove all '-' or '+'
Copy the code