Catalog
1.try...except, else, finally Use
2. String format output : a. In the string center,rjust, ljust
center
rjust
ljust
b. In a string format Use of methods ( With alignment , Width , Fill character )
c. Place holder : %d, %s, %f
d. New formatting : f/F( With alignment , Width , Fill character )
3. Use of the remaining string methods
capitalize
casefold
center
rjust
ljust
count
encode
decode
endswith
expandtabs
find
format
format_map
index
isalnum
isalpha
isascii
isdecimal
isdigit
isidentifier
* Add .python identifier
islower
isnumeric
isprintable
isspace
istitle
isupper
join
lower
lstrip
partition
removeprefix
removesuffix
replace
rfind
rindex
rpartition
rsplit
split
splitlines
startswith
strip
swapcase
title
translate
upper
zfill
4. Use input to complete the functions of the calculator : Input 7+8 Output : 7 + 8 = 15 Tips : Find whether there is... In the string "+/-*" Find one in the string split Method : Splits the string according to the specified character Get Two figures , And operation symbols
data = 1
try:
if data == 1:
raise ZeroDivisionError
except ZeroDivisionError:
data = 0
else:
data = 10
finally:
print("Finally")
print(data)
result
0
print("age".center(10, '*')) # Align center
print("20".center(10, '*'))
result
***age****
****20****
print("age".rjust(10, '*')) # Align right
print("20".rjust(10, '*'))
result
*******age
********20
print("age".ljust(10, '*')) # Align left
print("20".ljust(10, '*'))
result
age*******
20********
name = 'zhangsan'
age = 30
money = 999999999
print("My name is {:*^10} My age is {:*^10} My money is {:*^13}".format(name, age, money))
result
My name is *zhangsan* My age is ****30**** My money is **999999999**
print("My name is %s My age is %d My money is %.3f" % ('zhagnsan', 20, 999999.999))
result
My name is zhagnsan My age is 20 My money is 999999.999
name = 'zhangsan'
age = 30
print(f"My name is {name:*^10} My age is {age}")
result
My name is *zhangsan* My age is 30
capitalize
data = 'hello' print(data.capitalize()) result Hello
capitalize(self, /) title case
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower
case.casefold
data = 'HELLO' print(data.capitalize()) result Hello
casefold(self, /) Replace all with lowercase
Return a version of the string suitable for caseless comparisons.
center
print("age".center(10, '*')) # Align center print("20".center(10, '*')) result ***age**** ****20****
center(self, width, fillchar=' ', /) Align center
Return a centered string of length width.
Returns a string centered in length and width .
Padding is done using the specified fill character (default is a space).
Padding is done using the specified padding characters ( Default is space ).rjust
print("age".rjust(10, '*')) # Align right print("20".rjust(10, '*')) result *******age ********20
rjust(self, width, fillchar=' ', /) Right alignment
Return a right-justified string of length width.
ljust
print("age".ljust(10, '*')) # Align left print("20".ljust(10, '*')) result age******* 20********
ljust(self, width, fillchar=' ', /) Align left
Return a left-justified string of length width.
count
data = 'abcabcabc' print(data.count('a')) data = 'abcabcabc' print(data.count('abc')) result 3 3
count(...) Count , Count the number of occurrences of a character or string
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.encode
data = 'abc' print(data.encode('UTF-8')) result b'abc'
encode(self, /, encoding='utf-8', errors='strict') String encoded bytes
Encode the string using the codec registered for encoding.
decode
data = b'abc' print(data.decode('UTF-8')) result abc
decode decode ( Bytes decoded into strings )
encoding
The encoding in which to encode the string.
errors
The error handling scheme to use for encoding errors.
The default is 'strict' meaning that encoding errors raise a
UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
endswith
data = 'abcabcabc' print(data.endswith('c')) data = 'abcabcabc' print(data.endswith('bc')) data = 'abcabcabc' print(data.endswith('abc')) result True True True
endswith(...) Judge what ends with ( Can be a string )
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.expandtabs
data = 'abc\tabc' print(data.expandtabs(tabsize=9)) result abc abc
expandtabs(self, /, tabsize=8) There are no restrictions on extended tabs
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
find
data = 'abcabcabc' print(data.find('b')) result 1
find(...) Returns the smallest subscript
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
format
name = 'zhangsan' age = 30 money = 999999999 print("My name is {:*^10} My age is {:*^10} My money is {:*^13}".format(name, age, money)) result My name is *zhangsan* My age is ****30**** My money is **999999999**
format(...) format ( placeholder )
S.format(*args, **kwargs) -> str
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').format_map
data = 'abcabc666' data1 = 'abcd' print(data1.format_map(data)) print(data1) result abcd abcd
format_map(...) Use data1 Format and replace data
S.format_map(mapping) -> str
Return a formatted version of S, using substitutions from mapping.
The substitutions are identified by braces ('{' and '}').
index
data = 'abcabcdabcd' print(data.index('a')) result 0
index(...) return S The lowest index of the substring subitem found in
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
isalnum
data = 'abcabcdabcd123' print(data.isalnum()) data = 'abcabcdabcd123-' print(data.isalnum()) result True False
isalnum(self, /) If there are only characters or numbers in the string ( Or letters and numbers ), Then return to True, Otherwise return to False.
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and
there is at least one character in the string.
isalpha
data = 'abcabcdabcd123' print(data.isalpha()) data = 'abcabcdabcd' print(data.isalpha()) result False True
isalpha(self, /) If the string is an alphabetic string , Then return to True, Otherwise return to False.
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there
is at least one character in the string.
isascii
data = 'abcabcdabcd' print(data.isascii()) data = ' ha-ha ' print(data.isascii()) result True False
isascii(self, /) If all characters in the string are ASCII In the code table , Then return to True, Otherwise return to False.
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F.
Empty string is ASCII too.
isdecimal
data = 'x666' print(data.isdecimal()) data = '666' print(data.isdecimal()) result False True
isdecimal(self, /) If the string is a decimal string , Then return to True, Otherwise return to False.
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and
there is at least one character in the string.
isdigit
data = '666' print(data.isdigit()) data = '666abc' print(data.isdigit()) result True False
isdigit(self, /) If the string is a numeric string , Then return to True, Otherwise return to False.
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there
is at least one character in the string.
isidentifier
data = '666abc' print(data.isidentifier()) data = 'abc666' print(data.isidentifier()) result False True
isidentifier(self, /) If the string is valid Python identifier , Then return to True, Otherwise return to False.
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
such as "def" or "class".
* Add .python identifier
Python Naming rules for identifiers
- Python Identifier is created by 26 English letters in upper and lower case ,0-9 ,_ form .
- Python Identifier cannot begin with a number .
- Python Identifiers are strictly case sensitive .
- Python Identifier cannot contain spaces 、@、% as well as $ Equal special character .
- You cannot use system reserved keywords as identifiers ( Altogether 25 individual ).
islower
data = 'abc' print(data.islower()) data = 'ABC' print(data.islower()) result True False
islower(self, /) If the string is lowercase , Then return to True, Otherwise return to False.
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and
there is at least one cased character in the string.
isnumeric
data = '123' print(data.isnumeric()) data = '123a' print(data.isnumeric()) result True False
isnumeric(self, /) If the string is a numeric string , Then return to True, Otherwise return to False.
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at
least one character in the string.
isprintable
data = 'abc\nabc' print(data.isprintable()) data = 'abcabc' print(data.isprintable()) result False True
isprintable(self, /) If the string is printable , Then return to True, Otherwise return to False.
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in
repr() or if it is empty.
isspace
data = ' ' print(data.isspace()) data = 'a' print(data.isspace()) result True False
isspace(self, /) If the string is a space string , Then return to True, Otherwise return to False.
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there
is at least one character in the string.
istitle
data = 'Money' print(data.istitle()) data = 'MONEY' print(data.istitle()) data = 'money' print(data.istitle()) result True False False
istitle(self, /) If the string is a header case string , Then return to True, Otherwise return to False.
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only
follow uncased characters and lowercase characters only cased ones.isupper
data = 'ABC' print(data.isupper()) data = 'abc' print(data.isupper()) result True False
isupper(self, /) If the string is an uppercase string , Then return to True, Otherwise return to False.
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and
there is at least one cased character in the string.
join
print('-'.join(['bc', 'de'])) result bc-de
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
join(self, iterable, /) Connect any number of strings .
Concatenate any number of strings.
The string whose method is called is inserted in between each given string.
The result is returned as a new string.
Padding is done using the specified fill character (default is a space).
lower
data = 'ABC' print(data.lower()) result abc
lower(self, /) Returns a copy of a string converted to lowercase .
Return a copy of the string converted to lowercase.
lstrip
data = ' abc' print(data.lstrip(), data) result abc abc
lstrip(self, chars=None, /) Returns a copy of a string with leading spaces removed .
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
partition
data = 'ab|cd' print((data.partition('|'))) result ('ab', '|', 'cd')
partition(self, sep, /) Divide the string into three parts using the given delimiter .
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found,
returns a 3-tuple containing the part before the separator, the separator
itself, and the part after it. This will search the string for the delimiter . If the separator is found ,
Return to one 3 Tuples , It contains delimiters ( Separator ) The previous part
In itself , And the rest of it .
If the separator is not found, returns a 3-tuple containing the original string
and two empty strings. If the delimiter is not found , Returns... Containing the original string 3 Tuples
And two empty strings .
removeprefix
data = 'abc' print(data.removeprefix('a')) data = 'abc' print(data.removeprefix('ab')) result bc c
removeprefix(self, prefix, /) Returns a string with the given prefix removed ( If there is ) Of str.
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):].
Otherwise, return a copy of the original string.
removesuffix
data = 'abc' print(data.removesuffix('c')) data = 'abc' print(data.removesuffix('bc')) result ab a
removesuffix(self, suffix, /) Return to one str, If there is , Delete the given suffix string .
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty,
return string[:-len(suffix)]. Otherwise, return a copy of the original
string. If the string is followed by the end of the string , And the suffix is not empty ,
Return string [:-len( suffix )]. otherwise , Please return a copy of the original
character string .
replace
data = 'abc' print(data.replace('c', 'r')) result abr
replace(self, old, new, count=-1, /) Return a copy , It contains all the old substrings that appear , The substring has been replaced with new.( Replace all matching by default )
Return a copy with all occurrences of substring old replaced by new.
count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are
replaced.
rfind
data = 'abcabc' print(data.rfind('a')) result 3
rfind(...) return S The highest index of the substring subitem found in , bring sub Included in S[start:end] in
S.rfind(sub[, start[, end]]) -> int
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
rindex
data = 'abcabca' print(data.rindex('a')) result 6
rindex(...)
S.rindex(sub[, start[, end]]) -> int return S The highest index of the substring subitem found in ,
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
Padding is done using the specified fill character (default is a space).
rpartition
data = 'a|c' print(data.rpartition('|')) result ('a', '|', 'c')
rpartition(self, sep, /) Divide the string into three parts using the given delimiter .
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If
the separator is found, returns a 3-tuple containing the part before the
separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings
and the original string.
rsplit
data = 'a|c' print(data.rsplit(sep='|')) result ['a', 'c']
rsplit(self, /, sep=None, maxsplit=-1) Returns a list of words in a string , Use sep As a separator string .
Return a list of the words in the string, using sep as the delimiter string.
sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
Splits are done starting at the end of the string and working to the front. |
rstrip(self, chars=None, /)
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
split
data = 'abc' print(data.split(sep='b')) result ['a', 'c']
split(self, /, sep=None, maxsplit=-1) Returns a list of words in a string , Use sep As a separator string .
Return a list of the words in the string, using sep as the delimiter string.
sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
splitlines
data = 'abc\nabc' print(data.splitlines()) result ['abc', 'abc']
splitlines(self, /, keepends=False)
Return a list of the lines in the string, breaking at line boundaries.
Returns a list of rows in a string that are broken at the row boundary .
Line breaks are not included in the resulting list unless keepends is given and
true.
startswith
data = 'abc' print(data.startswith('a')) data = 'abc' print(data.startswith('b')) result True False
startswith(...)
S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.If S Start with the specified prefix , Then return to True, Otherwise return to False.
With optional start, test S beginning at that position.Use the optional start , test S Starting from that position .
With optional end, stop comparing S at that position.Use optional end , Stop comparing... At this position S.
prefix can also be a tuple of strings to try.
The prefix can also be a string tuple to try .strip
data = ' abc ' print(data.strip()) print(data) result abc abc
strip(self, chars=None, /) Returns a copy of a string with leading and trailing spaces removed .( Delete the space before and after )
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
swapcase
data = 'abcABC' print(data.swapcase()) result ABCabc
swapcase(self, /) Convert uppercase characters to lowercase , Convert lowercase characters to uppercase .
Convert uppercase characters to lowercase and lowercase characters to uppercase.
title
data = 'ABCabc' print(data.title()) result Abcabc
title(self, /) Returns a version of a string , The title of each word is capitalized .( title case , The rest are in lowercase )
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining
cased characters have lower case. More specifically , Words begin with uppercase characters , All other characters are Start with a capital letter , Upper and lower case characters have lowercase .
translate
data = 'abcabc' print(data.translate({ord('a'): 'A'})) result AbcAbc
Convert to Unicode Method
ord()
Example:ord('a')-> You can extract 'a' Of Unicode code
translate(self, table, /) Replace each character in the string with the given translation table .
Replace each character in the string using the given translation table.
table
Translation table, which must be a mapping of Unicode ordinals to
Unicode ordinals, strings, or None. Conversion table , It has to be Unicode Ordinal to
Unicode Serial number 、 String or none .
The table must implement lookup/indexing via __getitem__, for instance a
dictionary or list. If this operation raises LookupError, the character is
left untouched. Characters mapped to None are deleted.
upper
data = 'abcAbc' print(data.upper()) result ABCABC
upper(self, /) Returns a copy of a string converted to uppercase .
Return a copy of the string converted to uppercase.
zfill
data = 'abc' print(data.zfill(10)) result 0000000abc
zfill(self, width, /) Fill the numeric string with zeros on the left , To fill a field of a given width .
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
data = input(" Please enter the addition operation ")
# print(data.count('+'))
if data.count('+') == 1:
num = data.split("+")
x = int(num[0])
y = int(num[1])
print(x + y)
else:
print(' Please enter the addition operation ')
result
Please enter the addition operation 7+8
15
Process ended , Exit code 0