程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python的輸入及python中字符串的使用方法大全(超詳解)

編輯:Python

目錄

1.try...except, else, finally的使用

2.字符串格式化輸出:   a. 字符串中的center,rjust, ljust

center

rjust

ljust

b. 字符串中format方法的使用(帶對齊方式,寬度,填充字符)

   c. 占位符: %d, %s, %f

   d. 新的格式化: f/F(帶對齊方式,寬度,填充字符)

3.字符串剩余方法的使用

capitalize

casefold

center

rjust

ljust

count

 encode  

decode

endswith

expandtabs   

 find

 format

format_map 

index

 isalnum

 isalpha

isascii

isdecimal

 isdigit

 isidentifier

*補充.python標識符 

 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.使用輸入完成計算器的功能:  輸入 7+8 輸出: 7 + 8 = 15  提示:在字符串取查找是否有"+/-*"           找到字符串中有一個split方法:按照指定字符分割字符串           獲取到 兩個數字,以及運算符號


1.try...except, else, finally的使用

data = 1
try:
if data == 1:
raise ZeroDivisionError
except ZeroDivisionError:
data = 0
else:
data = 10
finally:
print("Finally")
print(data)
結果
0

2.字符串格式化輸出:
   a. 字符串中的center,rjust, ljust

center

print("age".center(10, '*')) # 居中對齊
print("20".center(10, '*'))
結果
***age****
****20****

rjust

print("age".rjust(10, '*')) # 向右對齊
print("20".rjust(10, '*'))
結果
*******age
********20

ljust

print("age".ljust(10, '*')) # 向左對齊
print("20".ljust(10, '*'))
結果
age*******
20********

b. 字符串中format方法的使用(帶對齊方式,寬度,填充字符)

name = 'zhangsan'
age = 30
money = 999999999
print("My name is {:*^10} My age is {:*^10} My money is {:*^13}".format(name, age, money))
結果
My name is *zhangsan* My age is ****30**** My money is **999999999**

   c. 占位符: %d, %s, %f

print("My name is %s My age is %d My money is %.3f" % ('zhagnsan', 20, 999999.999))
結果
My name is zhagnsan My age is 20 My money is 999999.999

   d. 新的格式化: f/F(帶對齊方式,寬度,填充字符)

name = 'zhangsan'
age = 30
print(f"My name is {name:*^10} My age is {age}")
結果
My name is *zhangsan* My age is 30

3.字符串剩余方法的使用

capitalize

data = 'hello'
print(data.capitalize())
結果
Hello

capitalize(self, /)  首字母大寫
       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())
結果
Hello

   casefold(self, /) 全部換成小寫
       Return a version of the string suitable for caseless comparisons.
   

center

print("age".center(10, '*')) # 居中對齊
print("20".center(10, '*'))
結果
***age****
****20****

   center(self, width, fillchar=' ', /) 居中對齊

       Return a centered string of length width.
       返回長度寬度居中的字符串。
       Padding is done using the specified fill character (default is a space).
       填充是使用指定的填充字符完成的(默認為空格)。

rjust

print("age".rjust(10, '*')) # 向右對齊
print("20".rjust(10, '*'))
結果
*******age
********20

    rjust(self, width, fillchar=' ', /) 右對齊

       Return a right-justified string of length width.

ljust

print("age".ljust(10, '*')) # 向左對齊
print("20".ljust(10, '*'))
結果
age*******
20********

 ljust(self, width, fillchar=' ', /) 左對齊

       Return a left-justified string of length width.
    

count

data = 'abcabcabc'
print(data.count('a'))
data = 'abcabcabc'
print(data.count('abc'))
結果
3
3

   count(...) 計數,統計字符或字符串的出現次數
       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'))
結果
b'abc'

   encode(self, /, encoding='utf-8', errors='strict')字符串編碼字節
       Encode the string using the codec registered for encoding.
 

decode

data = b'abc'
print(data.decode('UTF-8'))
結果
abc

 decode 解碼(字節解碼成字符串)
       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'))
結果
True
True
True

    endswith(...) 判斷以什麼結尾(可以是字符串)
       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))
結果
abc abc

   expandtabs(self, /, tabsize=8)擴展制表符沒有限制
       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'))
結果
1

   find(...)返回最小的下標
       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))
結果
My name is *zhangsan* My age is ****30**** My money is **999999999**

   format(...)格式化(占位)
       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)
結果
abcd
abcd

   format_map(...) 使用data1格式化並替換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'))
結果
0

   index(...)返回 S 中找到子字符串子項的最低索引
          
       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())
結果
True
False

   isalnum(self, /)如果字符串中只有字符或數字(或字母和數字),則返回 True,否則返回 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())
結果
False
True

   isalpha(self, /)如果字符串是字母字符串,則返回 True,否則返回 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 = '哈哈'
print(data.isascii())
結果
True
False

   isascii(self, /)如果字符串中的所有字符都是 ASCII碼表中的,則返回 True,否則返回 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())
結果
False
True

   isdecimal(self, /)如果字符串是十進制字符串,則返回 True,否則返回 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())
結果
True
False

   isdigit(self, /)如果字符串是數字字符串,則返回 True,否則返回 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())
結果
False
True

   isidentifier(self, /)如果字符串是有效的 Python 標識符,則返回 True,否則返回 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".
   

*補充.python標識符 

Python標識符的命名規則

  • Python 標識符由 26 個英文字母大小寫,0-9 ,_ 組成。
  • Python 標識符不能以數字開頭。
  • Python 標識符嚴格區分大小寫。
  • Python 標識符不能包含空格、@、% 以及 $ 等特殊字符。
  • 不能以系統保留關鍵字作為標識符(一共有25 個)。

 islower

data = 'abc'
print(data.islower())
data = 'ABC'
print(data.islower())
結果
True
False

  islower(self, /)如果字符串是小寫字符串,則返回 True,否則返回 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())
結果
True
False

   isnumeric(self, /)如果字符串是數字字符串,則返回 True,否則返回 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())
結果
False
True

   isprintable(self, /)如果字符串可打印,則返回 True,否則返回 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())
結果
True
False

   isspace(self, /)如果字符串是空格字符串,則返回 True,否則返回 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())
結果
True
False
False

   istitle(self, /)如果字符串是標題大小寫的字符串,則返回 True,否則返回 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())
結果
True
False

   isupper(self, /)如果字符串是大寫字符串,則返回 True,否則返回 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']))
結果
bc-de

   Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'

  join(self, iterable, /)連接任意數量的字符串。
       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())
結果
abc

   lower(self, /)返回轉換為小寫的字符串的副本。
       Return a copy of the string converted to lowercase.
   

lstrip

data = ' abc'
print(data.lstrip(), data)
結果
abc abc

   lstrip(self, chars=None, /)返回刪除了前導空格的字符串副本。
       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('|')))
結果
('ab', '|', 'cd')

   partition(self, sep, /)使用給定的分隔符將字符串劃分為三個部分。
       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.這將在字符串中搜索分隔符。 如果找到分隔符,
       返回一個 3 元組,其中包含分隔符(分隔符)之前的部分
       本身,以及它之後的部分。
       
       If the separator is not found, returns a 3-tuple containing the original string
       and two empty strings.如果未找到分隔符,則返回包含原始字符串的 3 元組
       和兩個空字符串。
   

removeprefix

data = 'abc'
print(data.removeprefix('a'))
data = 'abc'
print(data.removeprefix('ab'))
結果
bc
c

   removeprefix(self, prefix, /)返回一個刪除了給定前綴字符串(如果存在)的 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'))
結果
ab
a

   removesuffix(self, suffix, /)返回一個 str,如果存在,則刪除給定的後綴字符串。
       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.如果字符串以後綴字符串結尾,並且該後綴不為空,
       返回字符串[:-len(後綴)]。否則,請返回原件的副本
       字符串。
   

replace

data = 'abc'
print(data.replace('c', 'r'))
結果
abr

   replace(self, old, new, count=-1, /)返回一個副本,其中包含所有出現的舊子字符串,該子字符串已替換為 new。(默認替換所有匹配到的)
       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'))
結果
3

   rfind(...)返回 S 中找到子字符串子項的最高索引,使得 sub 包含在 S[start:end] 中
       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'))
結果
6

   rindex(...)
       S.rindex(sub[, start[, end]]) -> int 返回 S 中找到子字符串子項的最高索引,
       
       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('|'))
結果
('a', '|', 'c')

   rpartition(self, sep, /)使用給定的分隔符將字符串劃分為三個部分。
       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='|'))
結果
['a', 'c']

   rsplit(self, /, sep=None, maxsplit=-1)返回字符串中單詞的列表,使用 sep 作為分隔符字符串。
       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'))
結果
['a', 'c']

   split(self, /, sep=None, maxsplit=-1)返回字符串中單詞的列表,使用 sep 作為分隔符字符串。
       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())
結果
['abc', 'abc']

   splitlines(self, /, keepends=False)
       Return a list of the lines in the string, breaking at line boundaries.
       返回字符串中在行邊界處斷開的行的列表。


       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'))
結果
True
False

   startswith(...)
       S.startswith(prefix[, start[, end]]) -> bool
       
       Return True if S starts with the specified prefix, False otherwise.

       如果 S 以指定的前綴開頭,則返回 True,否則返回 False。


       With optional start, test S beginning at that position.

        使用可選的開始,測試 S 從該位置開始。


       With optional end, stop comparing S at that position.

       使用可選端,停止在該位置比較 S。 


       prefix can also be a tuple of strings to try.
       前綴也可以是要嘗試的字符串元組。

 strip

data = ' abc '
print(data.strip())
print(data)
結果
abc
abc 


   strip(self, chars=None, /)返回刪除了前導和尾隨空格的字符串副本。(刪除前後空格)
       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())
結果
ABCabc

   swapcase(self, /)將大寫字符轉換為小寫,將小寫字符轉換為大寫。
       Convert uppercase characters to lowercase and lowercase characters to uppercase.
   

title

data = 'ABCabc'
print(data.title())
結果
Abcabc

   title(self, /)返回字符串的一個版本,其中每個單詞的標題都大寫。(首字母大寫,其余小寫)
       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.更具體地說,單詞以大寫字符開頭,其余所有字符都         以大寫字母開頭,大小寫字符具有小寫。
   

translate

data = 'abcabc'
print(data.translate({ord('a'): 'A'}))
結果
AbcAbc

轉換為Unicode方法

     ord()

Example:ord('a')->就可以提取'a'的Unicode碼


   translate(self, 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.轉換表,它必須是 Unicode 序數到
           Unicode 序號、字符串或無。
       
       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())
結果
ABCABC

   upper(self, /)返回轉換為大寫的字符串的副本。
       Return a copy of the string converted to uppercase.
   

zfill

data = 'abc'
print(data.zfill(10))
結果
0000000abc

   zfill(self, width, /)在左側用零填充數字字符串,以填充給定寬度的字段。
       Pad a numeric string with zeros on the left, to fill a field of the given width.
       
       The string is never truncated.


4.使用輸入完成計算器的功能:
  輸入 7+8 輸出: 7 + 8 = 15
  提示:在字符串取查找是否有"+/-*"
           找到字符串中有一個split方法:按照指定字符分割字符串
           獲取到 兩個數字,以及運算符號

data = input("請輸入加法運算")
# print(data.count('+'))
if data.count('+') == 1:
num = data.split("+")
x = int(num[0])
y = int(num[1])
print(x + y)
else:
print('請輸入加法運算')
結果
請輸入加法運算7+8
15
進程已結束,退出代碼0

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved