Python string notes 2 ---

Common method string

In accordance with the built-in inside individually tested it and found that it is stupid to learn a language but a good way, as are the object methods that he removed the self in the summary of the time:
experience: programming is very important to read the document, the language will continue to change, Therefore, the method is not spent in mind, but they need to know the future operations of the destination string, go looking for methods
below method only class methods do not begin with an underscore. class method in the stitching and multiplying numbers of operator overloading methods currently on the first as a kind of operating it.

capitalize() Capitalized
casefold() For some non-English letters similar case mapping relationship
center(width, fillchar=None) The total width of the set width and then the content is centered, both filled with fillchar. Note that content may only be filled with a single character, and can be ignored, the default is a space
ljust(width, fillchar=None) Center and the like, is then filled from the left aligned
rjust(width, fillchar=None) Center and the like, is then filled from the right alignment
zfill(width) Starting from the left to fill 0, you can not be specified in order to fill what can only specify the width
count(sub,start=None,end = None) Calculate the number of sub appearing in the string, supporting characters and sequences, you can specify start and end, you can not specify
encode (encoding) and decode (encoding) This content when it comes to coding, behind the operation mode of the file in bytes can be encoded to be written is written or read in a certain way decoded.
expandtabs(tabsize=8) With the specified length \ t tabs into spaces 8 default
endswith(suffix,start=None,end =None) Returns a boolean determining whether the string corresponding to the string ends .suffix suffix may also be a tuple string. When it is time tuple, the tuple of elements as long as at least one condition is satisfied, return True, all not satisfied, return False.
startswith(prefix, start=None, end=None) Returns a boolean determining whether the string begins with a character string corresponding to .suffix suffix may also be a tuple string. When it is time tuple, the tuple of elements as long as at least one condition is satisfied, return True, all not satisfied, return False.
find(sub,start=None,end =None Looking from front to back in the character string sub sequences, finds the first index returns. If not found, returns -1. Note that, with the closing of the left and right open indexes are
rfind(sub, start=None, end=None) find versions starting from the right
format(*args, **kwargs) This is python string formatted content, the replacement string is the use of a placeholder value to learn .format specified separately
format_map(dict) Dictionary parameters given way, the key is the name dict placeholder, the value of the content is to be replaced
index(obj) Usage and find the same, but the index can not find the time will complain, rather than find the same return -1
rindex(sub, start=None, end=None) This is the index from the right, usage and find the same, but the index can not find the time will complain, rather than find the same return -1
isalnum () This is not only determined by the string of numbers and letters
Islf () Determining whether a string consisting only of letters, and at least one letter
isdecimal() This determination is not only composed of a string of decimal digits, and at least one number
isdigit () Determine whether the character string includes a decimal numbers and special characters
isnumeric() This has explained below, the support of the whole, including the number of Chinese characters can be recognized. Difference on isdecimal, isdigit and isnumeric in below
IDENTIFIER () This refers to whether the string complies with python identifier, that is, from alphanumeric and underscores, and can not begin with a number
islower() Determine whether all lowercase
isprintable () 这个是指是否只包含可以打印的字符,ASCII里的控制符都是不可打印字符
isspace() 所有字符是否都是空格
istitle() 所有字符是否符合首字母大写剩下字母小写,就是像英文的标题一样的格式
isupper() 所有字母是否都是大写
join(*args, **kwargs) 这是非常重要的一个方法,是分隔符.join(分割对象),而且很多其他数据类型也支持join方法
lower() 将字符串全部变成小写
upper() 将字符串全部变成大写
maketrans(*args, **kwargs) 这个要和translate一起讲,maketrans建立一个替换映射规则,然后用translate替换字符串.用的时候要调用str类该函数
translate(table) 用建立的映射关系table来替换字符串,用法示例看这里
lstrip(string) strip系列是去掉匹配的字符,默认是去掉空格,有lstrip,rstrip和strip,分别是从左边,从右边,从两边去掉.如果给出字符串参数,则会按照对象和参数的最长共同子序列不断匹配去掉,直到无法匹配为止.
rstrip(string) 属于strip系列
strip(string) 属于strip系列,strip系列在清洗字符串数据,获取用户输入等方面经常使用
partition(sep) 用sep分割字符串,只按照找到的第一个进行分割,分割成包含三部分的一个元组,sep是第二个元素,如果找不到sep,则分割出来的元组的后两项为空
rpartition(sep) partition从右边开始的版本
replace(old, new, count=None) 用new替换old,不指定次数则默认全部替换,否则替换count次
rsplit(sep=None, maxsplit=-1) 这是属于split系列,用sep分割,但是sep不再取回,默认全部分割,也可以指定分割次数
split(sep=None, maxsplit=-1) split系列,split是没有lspilt的,默认就是从左边开始
splitlines(keepends=None) 按照换行符\n来分割字符串,如果参数为True则每个分割的末尾会保留\n
swapcase() 切换字符串里的大小写,大写变小写,小写变大写
title() 格式化成英文标题一样的格式,每个单词的首字母大写,其他字母变成小写.

format的用法示例

test = 'I am {name}'
print(test.format(name="fd"))

.format_map的用法:

a = 'i am {name} {age} {marry}'
print(a.format_map({'name': 'minko', 'age': '32', 'marry': 'married'}))

format在占位符那里还有格式化控制方法,详细的可以以后再看.


python中str函数isdigit、isdecimal、isnumeric的区别:

num = “1” #unicode
num.isdigit() # True
num.isdecimal() # True
num.isnumeric() # True

num = “1” # 全角
num.isdigit() # True
num.isdecimal() # True
num.isnumeric() # True

num = b”1″ # byte
num.isdigit() # True
num.isdecimal() # AttributeError ‘bytes’ object has no attribute ‘isdecimal’
num.isnumeric() # AttributeError ‘bytes’ object has no attribute ‘isnumeric’

num = “IV” # 罗马数字
num.isdigit() # True
num.isdecimal() # False
num.isnumeric() # True

num = “四” # 汉字
num.isdigit() # False
num.isdecimal() # False
num.isnumeric() # True

===================
isdigit()
True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
False: 汉字数字
Error: 无

isdecimal()
True: Unicode数字,,全角数字(双字节)
False: 罗马数字,汉字数字
Error: byte数字(单字节)

isnumeric()
True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
False: 无
Error: byte数字(单字节)

================
import unicodedata

unicodedata.digit(“2”) # 2
unicodedata.decimal(“2”) # 2
unicodedata.numeric(“2”) # 2.0

unicodedata.digit(“2”) # 2
unicodedata.decimal(“2”) # 2
unicodedata.numeric(“2″) # 2.0

unicodedata.digit(b”3″) # TypeError: must be str, not bytes
unicodedata.decimal(b”3″) # TypeError: must be str, not bytes
unicodedata.numeric(b”3”) # TypeError: must be str, not bytes

unicodedata.digit(“Ⅷ”) # ValueError: not a digit
unicodedata.decimal(“Ⅷ”) # ValueError: not a decimal
unicodedata.numeric(“Ⅷ”) # 8.0

unicodedata.digit(“四”) # ValueError: not a digit
unicodedata.decimal(“四”) # ValueError: not a decimal
unicodedata.numeric(“四”) # 4.0

#”〇”,”零”,”一”,”壱”,”二”,”弐”,”三”,”参”,”四”,”五”,”六”,”七”,”八”,”九”,”十”,”廿”,”卅”,”卌”,”百”,”千”,”万”,”万”,”亿”


maketrans 和translate的用法示例:

test = 'gfdsaoiuuoiewiouifuosakjdskja'
a = str.maketrans("ge", "ab")
v = test.translate(a)
print(v)

其他字符串还可以使用的方法:

自学过C语言,知道字符串其实是一个字符数组,末尾以\0存放.字符串属于常量,因此一旦建立无法修改.python的一些内置函数也可以用于字符串,主要有:

  • len取长度
  • 索引
  • 切片
  • for循环

range的使用:

通过IDE里查看builtins,range也是一个类,基本用法是range(start, stop[, step]) 来生成一个range对象.

range(start, stop[, step]) 生成一个range对象,是一个iterator,每次调用生成左闭右开范围内的下一个数字,可以指定步长,默认为1
count(value) 检测value在range生成的队列里的次数
index(value, start=None, stop=None) 在range生成的队列里寻找指定值,返回索引,可以指定开始和结尾,找不到则报错

一些练习

# 实现一个简单的两个数字相加的加法器
# 实现一个简单的两个数字相加的加法器
content = input('请输入内容:')
content_clear = content.strip().replace(" ", "")
v1, v2 = content_clear.split('+')
# 对于元组内的元素可以用多重赋值来一次取得,这是很python的写法.
print(int(v1) + int(v2))
# 计算用户输入的内容中有几个十进制数字,几个字母
content = input('请输入内容: ')

num_li = []
char_li = []
num_count = 0
char_count = 0
for i in range(0, 10):
    num_li.append(str(i))
for i in range(65, 91):
    char_li.append(chr(i))
for i in range(97, 123):
    char_li.append(chr(i))
for i in content:
    if i in num_li:
        num_count += 1
    elif i in char_li:
        char_count += 1
    else:
        continue

print("十进制数字有{}个,字母有{}个,字符串的长度是{}.".format(
    num_count, char_count, len(content)))
# 制作随机验证码供用户输入,直到输入正确为止,若输入错误则重新生成验证码
import random


def randomcode():
    capt = ""
    for j in range(4):
        i = random.randint(0, 2)
        if i == 0:
            capt = capt + chr(random.randint(48, 57))
        elif i == 1:
            capt = capt + chr(random.randint(65, 90))
        else:
            capt = capt + chr(random.randint(97, 122))
    return capt


while(True):
    captcha = randomcode()
    user_input = input("请输入验证码{}: ".format(captcha))
    if user_input.strip() == captcha:
        print('输入正确')
        break
    else:
        continue
# 制作敏感词过滤系统
filter_list = ['苍井空', '东京热', '一本道', 'IPX']

content = input("请输入一段文字: ")

for i in range(len(filter_list)):
    content = content.replace(filter_list[i], "***")

print("过滤后的文字是:{}".format(content))
# 循环提示用户输入:用户名,密码,邮箱(长度不超过20,否则只有前20个有效),输入q或者Q表示退出,将用户输入以表格打印.
count = 0
name_li = []
password_li = []
mail_li = []
while(True):
    name = input('Please input name: ')
    if name == 'q' or name == 'Q':
        break
    password = input('Please input your password: ')
    if password == 'q' or password == 'Q':
        break
    mail = input('Please input your e-mail address:')
    if mail == 'q' or mail == 'Q':
        break
    if len(name) <= 20:
        name_li.append(name)
    else:
        name_li.append(name[:21])
    if len(password) <= 20:
        password_li.append(password)
    else:
        password_li.append(password[:21])
    if len(mail) <= 20:
        mail_li.append(mail)
    else:
        mail_li.append(mail[:21])
    count += 1
    
for i in range(count):
    print((name_li[i] + '\t' + password_li[i] +
           '\t' + mail_li[i]).expandtabs(22))

Guess you like

Origin www.cnblogs.com/bmxm/p/11927772.html
Recommended