Common methods of string learning in Python

catalogue

1. Join() function splicing: sep.join (iterable)

2. Case conversion:

(1) Method upper (): converts lowercase letters to uppercase letters.

(2) Method lower(): converts uppercase letters to lowercase letters.

(3) Method title (): the first letter of all words is uppercase, and the rest are lowercase

(4) Method capitalize(): converts the first character of a string to uppercase.

(5) Method swapcase(): convert uppercase to lowercase and lowercase to uppercase in the string.

3. Common retrieval methods:

(1) Method count(): counts the number of times the specified sub character appears in the string. (case sensitive)

(2) Method find (): find whether a string contains the queried substring.

(3) Method index (): find out whether a string contains the queried substring.

(4) Method startswitch(): query whether the string starts with the specified substring

(5) Method endswitch(): query whether the string ends with the specified substring

4. String segmentation:

(1) Method split(): slice the string by specifying a delimiter to split the string. (if no delimiter is specified, the blank string slice will be used by default, and there will be a list after cutting)

(2) Method splitless(): the string can only be sliced by the line delimiter to split the string. (you cannot specify a delimiter to slice the string. After cutting, it is a list)

(3) Method partition (): from the first position where str appears, divide the string into a 3-element tuple. (tuple after cutting)

5. String pruning:

(1) Method strip (): removes the character (blank or newline by default) or character sequence specified at the beginning and end of the string.

(2) Method lstrip(): removes the character (blank or newline by default) or character sequence specified in the string header.

(3) Method rstrip(): removes the character (blank or newline by default) or character sequence specified at the end of the string.

6. Three common string formats:

(1)%-formatting

(2)str.format()

(3)f-string

1. Join() function splicing: sep.join (iterable)

Explanation: use sep as separator to combine all elements in iterable into a new string.

list_val = ['www','baidu','com']
str_val = '.'.join(list_val)
print(str_val)

tuple = ('User','andy','code')
str_val = '/'.join(tuple)
print(str_val)

Operation results:

2. Case conversion:

(1) Method upper (): converts lowercase letters to uppercase letters.

(2) Method lower(): converts uppercase letters to lowercase letters.

(3) Method title (): the first letter of all words is uppercase, and the rest are lowercase

(4) Method capitalize(): converts the first character of a string to uppercase.

(5) Method swapcase(): convert uppercase to lowercase and lowercase to uppercase in the string.

str1 = 'I love Python'
str2 = str1.upper()
str3 = str1.lower()
str4 = str1.title()
str5 = str1.capitalize()
str6 = str1.swapcase()
print(str2,str3,str4,str5,str6,sep = '\n')

Operation results:

3. Common retrieval methods:

(1) Method count(): counts the number of times the specified sub character appears in the string. (case sensitive)

str.count ("string to be retrieved", starting position and ending position of retrieval)

Note: the start position and end position can be omitted. It defaults to the first character to the last character, and the index value of the first character is 0.

str = "LoveYouPython"
print(str.count("o"))
print(str.count("O"))

Operation results:

 

(2) Method find (): find whether a string contains the queried substring.

str.find ("string to be retrieved", starting position and ending position of retrieval)

Note: if the first substring to be queried is found, this method returns the index of the string. Otherwise, - 1 is returned, which means that the string is not found.

str = "LoveYouPython"
print(str.find("o"))
print(str.find("O"))

Operation results:

 

(3) Method index (): find out whether a string contains the queried substring.

str.index ("retrieved string", starting position and ending position of retrieval)

Note: if the first substring to be queried is found, this method returns the index of the string. Otherwise, an exception is returned, indicating that the string is not found.

str = "LoveYouPython"
print(str.index("o"))

Operation results:

str = "LoveYouPython"
print(str.index("O"))

Operation result: error

(4) Method startswitch(): query whether the string starts with the specified substring

Str.startswitch ("string to be retrieved", starting position and ending position of retrieval)

Note: return True if found, otherwise return False.

str = "LoveYouPython"
print(str.startswith("L"))
print(str.startswith("o"))

Operation results:

 

(5) Method endswitch(): query whether the string ends with the specified substring

Str.endswitch ("string to be retrieved", starting position and ending position of retrieval)

Note: return True if found, otherwise return False.

str = "LoveYouPython"
print(str.endswith("n"))
print(str.endswith("o"))

Operation results:

4. String segmentation:

(1) Method split(): slice the string by specifying a delimiter to split the string. (if no delimiter is specified, the blank string slice will be used by default, and there will be a list after cutting)

str.split ("delimiter", number of splits)

(2) Method splitless(): the string can only be sliced by the line delimiter to split the string. (you cannot specify a delimiter to slice the string. After cutting, it is a list)

(3) Method partition (): from the first position where str appears, divide the string into a 3-element tuple. (tuple after cutting)

str.partition(string_pre_str,str,string_post_str)

str1 = "I love\t you\nPy\rthon"
print(str1.split())
str2 = "I love you so much Py old thon"
print(str2.split("old",2))
str3 = "I love\r you\nPy\r\nthon"
print(str3.splitlines())
str4 = "LoveYouPython"
print(str4.partition("o"))

Operation results:

5. String pruning:

(1) Method strip (): removes the character (blank or newline by default) or character sequence specified at the beginning and end of the string.

str.strip ([chars]) chars: removes the character sequence specified at the beginning and end of the string

Note: this method can only delete the characters at the beginning or end, not the characters in the middle.

str = " Love Python\n\t\r "
print(str.strip())

Operation results:

(2) Method lstrip(): removes the character (blank or newline by default) or character sequence specified in the string header.

str.lstrip ([chars]) chars: removes the character sequence specified in the string header

Note: this method can only delete the beginning characters, not the middle and end characters.

str = " Love Python\n\t\r "
print(str.lstrip())

Operation results:

(3) Method rstrip(): removes the character (blank or newline by default) or character sequence specified at the end of the string.

str.rstrip ([chars]) chars: removes the character sequence specified at the end of the string

Note: this method can only delete the characters at the end, not the characters at the middle and beginning.

str = " Love Python\n\t\r "
print(str.rstrip())

Operation results:

6. Three common string formats:

(1)%-formatting

name = 'Aaron'
login_time = 10
cost = 258.88
print('Hello%s,Welcome to login! This is the second time you logged in%d Times. Your current consumption%.2f element' % (name,login_time,cost))
# Dictionary situation
data = {'name':'Aaron','login_time':10,'cost':258.88}
tuple_value = (data['name'],data['login_time'],data['cost'])
print('Hello%s,Welcome to login! This is the second time you logged in%d Times. Your current consumption%.2f element' % tuple_value)

Operation results:

(2)str.format()

Replace the previous% with {} and:

Unlimited parameters can be accepted, and the position can not be in order.

name = 'Aaron'
login_time = 10
cost = 258.8890
print('Hello{},Welcome to login! This is the second time you logged in{}Times. Your current consumption{:.2f}Yuan.'.format(name,login_time,cost))
print('Hello{},Welcome to login! This is the second time you logged in{}Times. Your current consumption{:.2f}Yuan. congratulations{}become vip. '.format(name,login_time,cost,name))
print('Hello{0},Welcome to login! This is the second time you logged in{1}Times. Your current consumption{2:.2f}Yuan. congratulations{0}become vip. '.format(name,login_time,cost))
print('Hello{name},Welcome to login! This is the second time you logged in{log_time}Times. Your current consumption{cost:.2f}Yuan. congratulations{name}become vip. '.format(name=name,log_time=login_time,cost=cost))
# Dictionary situation
data = {'name':'Aaron','login_time':10,'cost':258.88}
print('Hello{},Welcome to login! This is the second time you logged in{}Times. Your current consumption{}element'.format(data['name'],data['login_time'],data['cost']))

Operation results:

(3)f-string

String led by f or F modifier (f 'xxx' or F 'xxx')

The replaced field is indicated by braces {}

name = 'Aaron'
login_time = 10
cost = 258.8890
print(f'Hello{name},Welcome to login! This is the second time you logged in{login_time}Times. Your current consumption{cost:.2f}Yuan.')
print(f'Hello{name},Welcome to login! This is the second time you logged in{login_time}Times. Your current consumption{cost:.2f}Yuan. congratulations{name}become vip. ')
# Dictionary situation
data = {'name':'Aaron','login_time':10,'cost':258.88}
print(f'Hello{name},Welcome to login! This is your login page{login_time}Times. Your current consumption{cost:.2f}Yuan. congratulations{name}become vip. ')

Operation results: 

 

Keywords: Python Windows Pycharm

Added by gr8dane on Thu, 03 Feb 2022 02:44:52 +0200