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

Posted Gur.

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

python2.7,输入一个字符串,统计其中每个字符出现的次数(不区分大小写),使用列表及字符串函数

python2.7,输入一个字符串,统计其中每个字符出现的次数(不区分大小写),使用列表及字符串函数
提示:
str=’abcda’
x=str.count(‘a’)可以统计’a’的出现次数
list.append(x)可用于存储字符的个数到列表中

参考技术A str=input("请输入一串字符")
str1=str.lower()
str2=
for i in str1:
str2[i]=str1.count(i)
print(str2)
参考技术B s = input().lower()
result = [[e, s.count(e)] for e in set(list(s))]
print(result)

参考技术C result = [str.count(e) for e in set(list(str)) ]

记得给我个最佳
参考技术D str1=input().lower()
i=input()
count=str1.count(i)
print(count)

以上是关于python的输入及python中字符串的使用方法大全(超详解)的主要内容,如果未能解决你的问题,请参考以下文章

Python输入输出及运算符

Python的用户交互程序及格式化输出

Python接收输入一个字符串,统计其中小写字母的个数

python编码及类型转换

python数据类型及有关的实用函数

Python25道练习题及详细答案解析,爆肝八小时总结