python中str详解

目录

字符串对象

str概念定义

内置函数

1.对齐方式

2.count(...)

3.开始、结尾

4. index(...) 

5.格式化字符串

5.1format(...)

5.2 format_map(...) 

6.is--表判断

7.replace 替换

8.移除前后缀

8.1 removeprefix

8.2 removesuffix

9.拆分与加入

9.1 split

9.2 rsplit

9.3 join

9.4 partition

10.清除空格

10.1 strip

10.2 rstrip()

10.3 lstrip()

11.转大写小写以及标题

        11.1 upper

11.2 lower

11.3 title

* 12.编码与解码

12.1 encode

12.2 bytes >> decode

13.密码本与加密

13.1 maketrans 制作密码本

13.2 translate 加密


字符串对象

str概念定义

1.python字符串是基本数据类型, python同时也是一门面向对象编程语言,
在面向对象的编程语言中, 所有的类型,包括基本数据类型,都是有对应的对象的,
在面向对象的编程语言来看 , 万物兼对象!!!

2.字符串本质就是一串字符数组, 也是一个可迭代对象
具有有下标, 可以通过下标来访问字符串中某个字符
3.可以转换成列表  list()
4.字符串的表达形式:
str_data = ' '
str_data =''' '''
str_data =" "
str-data =""" """

内置函数

1.对齐方式

对齐方式(有返回值)
__center()  居中对齐
__ljust()   左对齐
__rjust()   右对齐
对齐函数使用方法都一样则用ljust举例
1 ljust(self, width, fillchar=' ', /)(自(可省略),宽度,填充字符=‘’,/)
      Return a left-justified string of length width.
      返回长度宽度为左对齐的字符串。
     Padding is done using the specified fill character (default is a space).
     填充使用指定的填充字符(默认值为空格)。
str_data = 'this is a pig'
print(str_data.center(20, '$'))        # 结果$$$this is a pig$$$$
print(str_data.ljust(20, '*'))         # 结果this is a pig*******
print(str_data.rjust(20, '_'))         # 结果_______this is a pig

2.count(...)

count(...)    计数(元素)有返回值
str_data = 'sajdhkdscgauycvahbhcjdfuyvceg'
print(str_data.count('h'))        # 结果3

3.开始、结尾

startswith(...)      判断以...开始   有返回值
endswith(...)        判断以...结束   有返回值
由于startswith()与endswith() 函数语用法一样,故举例startswith()  
   startswith(...)开始(...)
       S.startswith(prefix[, start[, end]]) -> bool
       开始([前缀[,开始[,结束]]->bool)
       Return True if S starts with the specified prefix, False otherwise.
       如果S以指定前缀开头,则返回True,否则为Talse。
       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.
       前缀也可以是要尝试的字符串的元组
 
str_data = 'hello word'
print(str_data.endswith('word'))
print(str_data.endswith('rd'))
print(str_data.endswith('g'))
print(str_data.startswith('hello'))
print(str_data.startswith('h'))
print(str_data.startswith('hrl'))
输出结果
'''
D:\AXXZX\Python\python\python.exe D:\python_code\str.py 
True
True
False
True
True
False

Process finished with exit code 0
'''      

4. index(...) 

 index(...)   通过元素查找下标

str_data = 'abcdabadddda'
pos = str_data.index("a")
pos1 = str_data.index('a', pos+1)
pos2 = str_data.index('a', pos1+1)
pos3 = str_data.index('a', pos2+1)
print(pos, pos1, pos2, pos3)        # 结果 0 4 6 11

5.格式化字符串

5.1format(...)

format(...)格式(序列或者字典)
     S.format(*args, **kwargs) -> str    格式(*args,**kwargs)->str
     Return a formatted version of S, using substitutions from args and kwargs.
     使用args和kwargs的替换返回格式化的S版本。
     The substitutions are identified by braces ('{' and '}'). 
      用大括号(“{”和“}”)标识替换。 
# 例.使用字符串格式化方法format打印此列表:
# 打印效果如下(学号,姓名,语文成绩,数学成绩,英语成绩, 居中对齐):
# stu_id      name     Chinese  Math English
# 04101041  zhangsan      90     Math   100
stu_list = [
{"stu_id": "stu_id", "name": "name", "Chinese": "Chinese", "Math": "Math", "English": "English"},
    {"stu_id": "04101041", "name": "zhangsna", "Chinese": 90, "Math": 80, "English": 100},
    {"stu_id": "04101042", "name": "lisi", "Chinese": 70, "Math": 80, "English": 90},
    {"stu_id": "04101043", "name": "wangwu", "Chinese": 76, "Math": 96, "English": 80},
]
for i in stu_list:
    print("{0[stu_id]:^20}{0[name]:^20}{0[Chinese]:^10}{0[Math]:^10}{0[English]:^10}".format(i))
# 运行结果
'''
D:\AXXZX\Python\python\python.exe D:\python_code\str.py 
       stu_id               name         Chinese     Math    English  
      04101041            zhangsna          90        80       100    
      04101042              lisi            70        80        90    
      04101043             wangwu           76        96        80    

Process finished with exit code 0

'''

5.2 format_map(...) 

format_map(...)  格式地图(...)
     S.format_map(mapping) -> str    字符串(映射)
     Return a formatted version of S, using substitutions from mapping.
     返回S的格式化版本,使用映射中的替换。
     The substitutions are identified by braces ('{' and '}').
      这些替换用大括号('{'和'}')表示。
stu_list = [
    {"stu_id": "stu_id", "name": "name", "Chinese": "Chinese", "Math": "Math", "English": "English"},
    {"stu_id": "04101041", "name": "zhangsna", "Chinese": 90, "Math": 80, "English": 100},
    {"stu_id": "04101042", "name": "lisi", "Chinese": 70, "Math": 80, "English": 90},
    {"stu_id": "04101043", "name": "wangwu", "Chinese": 76, "Math": 96, "English": 80},
]
for i in stu_list:
    print("{stu_id:^20}{name:^20}{Chinese:^10}{Math:^10}{English:^10}".format_map(i))
# 运行结果
'''
D:\AXXZX\Python\python\python.exe D:\python_code\str.py 
       stu_id               name         Chinese     Math    English  
      04101041            zhangsna          90        80       100    
      04101042              lisi            70        80        90    
      04101043             wangwu           76        96        80    

Process finished with exit code 0
'''

6.is--表判断

'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 
   'islower', 'isnumeric', 'isprintable','isspace', 'istitle', 'isupper',
以is**开头的都是用来判断字符串是否符合某种规则,最后返回bool。有返回值
__islower()判断字符串是否都为小写
__isupper()判断字符串是否都为大写
__istitle()判断字符串是否为标题(标题:每个单词首字母都大写)
__isalnum()判断字符串是否由大小写字母,数字组成
__isalpha()判断字符串是否全部都由字母组成
__isascii()判断字符串是否全部都由ASCII码组成
__isdecimal()判断字符串是否是由十进制数字组成
__isdigit()判断字符串是否是数字字符串
__isnumeric()判断字符串是否是数字字符串
__isidentifier()判断字符串是否符合变量命名规范         
__isspace()判断字符串是否是空白字符串
__isprintable()判断字符串是否可以打印
print('HELLO WORD'.isupper())   # True
print("hello word".isupper())   # False
print("hello word".islower())   # True
print('Hello Word'.islower())   # False
print('Hello Word'.istitle())   # True
print('HELLO WORD'.istitle())   # False
print("shajAHS213".isalnum())   # True
print("shajAHS23_".isalnum())   # False
print("shajAHSdds".isalpha())   # True
print("shajAHS213".isalpha())   # False
print('shd_.,@#$%'.isascii())   # True
print('你好呀,世界。'.isascii())  # False
print('           '.isspace())  # True
print('你好呀,世界。'.isspace())  # False
print("32445412334".isdigit())  # True
print("adsiaj12334".isdigit())  # False
print('22222223233'.isnumeric())  # True
print('csgdh223233'.isnumeric())  # False

7.replace 替换

replace(self, old, new, count=-1, /)     替换(自己, 旧的, 新的,计数=-1, /)
      Return a copy with all occurrences of substring old replaced by new.
            返回一个副本,将所有出现的子字符串old替换为new。
     If the optional argument count is given, only the first count occurrences are replaced.
    如果给定可选参数计数,则只有第一个计数出现被取代。
   
print("hello word".replace("word", "boy"))     # 输出结果 hello boy 

8.移除前后缀

8.1 removeprefix

 removeprefix(self, prefix, /)  移除前缀(自,前缀,/)
str_data = 'hello word'
print(str_data.removeprefix('he'))       # llo word

8.2 removesuffix

removesuffix(self, suffix, /)  移除后缀(自,后缀,/)
str_data = 'hello word'
print(str_data.removesuffix("rd"))       # hello wo

9.拆分与加入

9.1 split

split(self, /, sep=None, maxsplit=-1)   切割字符串(自己, /, sep=空, 最大拆分=-1)
        Return a list of the substrings in the string, using sep as the separator string.
        返回字符串中子字符串的列表,使用sep作为分隔符字符串。
        sep
           The separator used to split the string. 用于拆分字符串的分隔符。
        When set to None (the default value), will split on any whitespace
        当设置为None(默认值)时,将在任何空格上拆分
        character 
            (including \\n \\r \\t \\f and spaces) and will discard empty strings from          the result.        
            字符(包括\\n\\r\t\f和空格),并将放弃结果中的空字符串。
        maxsplit  最大拆分
            Maximum number of splits (starting from the left). -1 (the default value)         means no limit.
            最大拆分次数(从左侧开始)。—1(默认值)表示没有限制。
        Note, str.split() is mainly useful for data that has been intentionally
        delimited.  With natural text that includes punctuation, consider using
        the regular expression module.
        附注,str.split()主要用于那些被有意添加的数据。分隔的。对于包含标点符号的自然文本,请考虑使用正则表达式模块。
 # 用‘.’拆分字符串串
str_data = "www.baidu.com"
print(str_data.split('.'))    # 输出结果['www', 'baidu', 'com']

print('hello word'.split())   # 输出结果['hello', 'word']
# 此时,默认在任何空格上拆分

9.2 rsplit

rsplit(self, /, sep=None, maxsplit=-1)(自己,/,sep=无,最大拆分=-1)
    rsplit与split用法相同不同点在于rsplit拆分从字符串的末尾开始
    Splitting starts at the end of the string and works to the front.
      拆分从字符串的末尾开始,一直工作到前面。
str_data = "www.baidu.com"
print(str_data.rsplit('.'))     # 输出结果['www', 'baidu', 'com']
print("hello word".rsplit())    # 输出结果['hello', 'word']  

9.3 join

join(self, iterable, /)  加入(自我,可迭代,/)
  Concatenate any number of strings.  将任意数目的字符串连在一起
  Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
例:‘.’.联接(‘ab’,‘pq’,‘rs’)->‘ab.pq.rs’
srt_list = ['www', 'baidu', 'com']
print('.'.join(srt_list))       # 输出结果 www.baidu.com
srt_list = ['hello', 'word']
print(" ".join(srt_list))        # 输出结果 hello word 

9.4 partition

partition(self, sep, /)  分区(自分区,分区)
 将字符串分为三部分“第一部分,第一个分割符, 剩余部分” 
 str_data = "man1, man2, man3, man4"
    print(str_data.partition(','))     # 输出结果 ('man1', ',', ' man2, man3, man4')

10.清除空格

10.1 strip

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.
      如果给定的字符不是None,则删除字符中的字符。
print('    hello word     '.strip())       # hello word

10.2 rstrip()

rstrip()  清楚右侧空格 
 print('hello word    '.rstrip())             # hello word

10.3 lstrip()

strip()  清除左侧空格    
 print('   hello word'.lstrip())             # hello word  

11.转大写小写以及标题

11.1 upper

 upper(self, /)  转大写(自己,/)
    Return a copy of the string converted to uppercase.返回转换为大写的字符串的副本。
print('hello word hello boy'.upper())       # HELLO WORD HELLO BOY

11.2 lower

lower(self, /)  转小写(自己,/)
     Return a copy of the string converted to lowercase.返回转换为小写的字符串的副本
print('HELLO WORD HELLO BOY'.lower())       # hello word hello boy

11.3 title

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.
     更具体地说,单词以超感知字符和所有剩余字符开头大写字符大小写。
print('hello word hello boy'.title())       # Hello Word Hello Boy
print('HELLO WORD HELLO BOY'.title())       # Hello Word Hello Boy

* 12.编码与解码

12.1 encode

 encode(self, /, encoding='utf-8', errors='strict')  编码(self,/,编码=utf-8,错误=严格)
     将字符串转换成字节来处理
     Encode the string using the codec registered for encoding.
        使用注册用于编码的编解码器对字符串进行编码。
      encoding 编码
         The encoding in which to encode the string.对字符串进行编码的编码。
      errors 错误
         The error handling scheme to use for encoding errors. 用于编码错误的错误处理方案
         UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and
         'xmlcharrefreplace' as well as any other name registered with
         codecs.register_error that can handle UnicodeEncodeErrors.  
        用于编码错误的错误处理方案   默认值为“strict”意味着编码错误会引发一个UnicodeEncodeError.  
        其他可能的值有“忽略”、“替换”和“xmlcharrefreplace”以及任何其他注册于可以处理
str_data = "你好"
print(str_data.encode(encoding='utf-8'))
# 输出结果 b'\xe4\xbd\xa0\xe5\xa5\xbd'

12.2 bytes >> decode

bytes >> decode
bytes 字节
decode(self, /, encoding='utf-8', errors='strict')   解码(自,/,编码=utf-8,错误=严格)
将字节转换为字符串
      Decode the bytes using the codec registered for encoding.
        使用注册用于编码的编解码器对字节进行解码。
      encoding  编码
       The encoding with which to decode the bytes.用来解码字节的编码。
      errors 错误
        The error handling scheme to use for the handling of decoding errors. 用于处理解码错误的错误处理方案。  
        The default is 'strict' meaning that decoding errors raise a
        UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
        as well as any other name registered with codecs.register_error that
        can handle UnicodeDecodeErrors.
         默认值为“strict”,这意味着解码错误会引发Unicode Code Error其他可能的值
         是“忽略”和“替换”以及在codecs.register_error中注册的任何其他名称可以处理Unicode编码错误。
bytes_data = b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(bytes_data.decode(encoding='utf-8'))
# 输出结果 你好 

13.密码本与加密

13.1 maketrans 制作密码本

 maketrans(...)制作密码本
    Return a translation table usable for str.translate().
    返回一个可用于str.translate()的转换表。
    If there is only one argument, it must be a dictionary mapping Unicode
    ordinals (integers) or characters to Unicode ordinals, strings or None.
    Character keys will be then converted to ordinals.
    If there are two arguments, they must be strings of equal length, and
    in the resulting dictionary, each character in x will be mapped to the
    character at the same position in y. If there is a third argument, it
    must be a string, whose characters will be mapped to None in the result.
    如果只有一个参数,那么它一定是一个字典映射国际标准组织10646标准序数(整数)
    或字符转换为Unicode序数、字符串或None。然后将字符键转换为序数。如果有两个参数,
    它们必须是长度相等的字符串,并且在生成的字典中,x中的每个字符都将被映射到字符在y中的相同位置。
    如果有第三个参数,它必须是一个字符串,其字符将被映射到结果中的None
# 制作一个密码本
table = "".maketrans({'h': "hhh", "e": 'eee', 'l': "lll", 'o': "ooo",  'w': "www", "r": "rrr", 'd': "ddd"})
print(table)    
# 输出结果 {104: 'hhh', 101: 'eee', 108: 'lll', 111: 'ooo', 119: 'www', 114: 'rrr', 100: 'ddd'}

13.2 translate 加密

加密一段字符串
table = "".maketrans({'h': "hhh", "e": 'eee', 'l': "lll", 'o': "ooo",  'w': "www", "r": "rrr", 'd': "ddd"})  
str_data = 'hello word'
print(str_data.translate(table))
# 输出结果 hhheeellllllooo wwwooorrrddd

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
当您需要将变量插入到字符串时,您可以使用Python的字符串格式化方法 `str.format()`。以下是一些用法示例: 1. 基本用法 您可以使用一对大括号 `{}` 来表示需要插入变量的位置,然后通过 `str.format()` 方法将变量传递进去。例如: ```python name = 'Alice' age = 25 print('My name is {}, and I am {} years old.'.format(name, age)) ``` 输出结果为:`My name is Alice, and I am 25 years old.` 2. 指定变量位置 如果您希望在字符串指定变量的位置,您可以在大括号内指定变量的索引位置。例如: ```python name = 'Alice' age = 25 print('My name is {0}, and I am {1} years old.'.format(name, age)) ``` 输出结果为:`My name is Alice, and I am 25 years old.` 3. 使用变量名称 如果您希望在字符串使用变量的名称而不是位置,您可以在大括号内指定变量的名称。例如: ```python name = 'Alice' age = 25 print('My name is {n}, and I am {a} years old.'.format(n=name, a=age)) ``` 输出结果为:`My name is Alice, and I am 25 years old.` 4. 格式化数字 您可以使用不同的格式指定符号来格式化数字,例如指定小数点后的位数,使用千位分隔符等等。例如: ```python x = 123.456 print('The value of x is {:.2f}'.format(x)) # 保留两位小数 print('The value of x is {:,}'.format(x)) # 添加千位分隔符 ``` 输出结果为:`The value of x is 123.46` 和 `The value of x is 123.456` 以上是 `str.format()` 方法的一些常见用法,希望对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱玩网络的小石

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值