Catalog
1、 Determine whether the string is based on “A” At the beginning
2、 Remove the contents at the beginning and end of the string
3、 De duplicate the string
4、 Sort the values of strings
Using functions startswith() Judge the beginning of the content .(startswith( String to judge ), If it is to judge whether it ends with a certain character , Then use endswith())
a = "Atom" # Define a variable a The value of is "Atom"
print(a.startswith("A")) # Using functions startswith() Judge whether it is based on A start The result is :True
Using functions strip() Go to the beginning and end of the string (strip( What to remove ), If you want to remove a character at the beginning, use lstrip(), If you want to remove a character at the end, use rstrip())
b = "!!!Atom!!" # Define a variable b The value of is "!!!Atom!!"
print(b.strip("!")) # Use built-in functions strip() Remove the head and tail ! The result is :Atom
There are two common methods to remove duplicate strings
(1) Change the string into a set , And then with join() Functions are spliced into strings ( Because the elements in the set cannot be repeated )
c = "djkaljdkla" # Define a variable d The value of is "djkaljdkla"
d = set(c) # Because sets cannot be repeated , So put variables b Become a collection c
print(d) # The result is :{'d', 'l', 'k', 'j', 'a'}( Because the set is disordered, the order of printing results may be different each time )
print("".join(d)) # And then use join() Functions are concatenated into a string The result is :aljdk( Because the set is disordered, the order of printing results may be different each time )
(2) You can define an empty list first , Then iterate through the string , After that, we have a test if Judge , If this is not in the list, add it to the list , In this way, the weight is removed .
c = "djkaljdkla" # Define a variable c The value of is "djkaljdkla"
d = [] # Define an empty list d
for i in c: # The string c Traverse
if i not in d: # Judge each value traversed , If there is this value in the list, judge the next value , If there is no such value in the list, enter the subcode
d.append(i) # Add this value to the end of the list
print(d) # The result of printing is :['d', 'j', 'k', 'a', 'l']
print("".join(d)) # In use at this time join() Function to splice The result is :djkal
have access to sorted() Function to sort (sorted( Iteratable objects that need to be sorted ))
c = "djkaljdkla" # Define a variable c The value of is "djkaljdkla"
print(sorted(c)) # Use sorted() Function to variable c Sort Print the results :['a', 'a', 'd', 'd', 'j', 'j', 'k', 'k', 'l', 'l']
print("".join(sorted(c))) # Use join() Function to sort the variables c Splicing The result is :aaddjjkkll
The official account is two-dimensional code. , The content is sent out synchronously , We can focus on learning together
This is the official account of Zhang Gouzi's brother brother. , Will share some of the usual work experience , You can pay attention to .