python basis - string type built-in method

String type built-in method (str)

1. Purpose: describe the nature of things, such as the person's name, a single loving, address, country, etc.

2. Definitions: Use '', '', '' '' '' "" "" "" wrapped string of characters

 * U'unicode ': unicode string encoded
 * b'101': binary coded string
 * r '\ n': original string, that is to say '\ n' which is an ordinary two characters, and no line change means

name = 'nick'  # name =str('nick')
s1 = str(1.1)
s2 = str([1, 2, 3])

print(f's1:{s1}, type:{type(s1)}')
print(f's2:{s2}, type:{type(s2)}')

s1:1.1, type:<class 'str'>
s2:[1, 2, 3], type:<class 'str'>
3. common operations + built-in method: built-in methods and common operations are divided into priority master (today have to remember), need to have (within a week to remember), other operations (understand) in three parts.

Priority control (*****)

 1. Press the index value

 2. Slice

 3. length len

 4. member operator in | not in

 5. Remove the blank strip

 6. Segmentation split

 7. The cycle
1. Press index values (not only desirable change)

# str索引取值
msg = 'hello nick'
#      0123456789  # 索引序号

print(f'索引为6: {msg[6]}')
print(f'索引为-3: {msg[-3]}')

索引为6: n
索引为-3: i

2. Section (care regardless of the end, step)

# 索引切片
msg = 'hello nash'
#      0123456789  # 索引序号

print(f'切片3-最后: {msg[3:]}')
print(f'切片3-8: {msg[3:8]}')
print(f'切片3-8,步长为2: {msg[3:8:2]}')
print(f'切片3-最后,步长为2: {msg[3::2]}')

# 了解,步长为正从左到右;步长为负从右到左
print('\n**了解知识点**')
print(f'切片所有: {msg[:]}')
print(f'反转所有: {msg[::-1]}')
print(f'切片-5--2: {msg[-5:-2:1]}')
print(f'切片-2--5: {msg[-2:-5:-1]}')

切片3-最后: lo nash
切片3-8: lo na
切片3-8,步长为2: l i
切片3-最后,步长为2: l sh

**了解知识点**
切片所有: hello nash
反转所有: hsan olleh
切片-5--2: ni
切片-2--5: san

3. length len

# str长度
msg = 'hello nash'

print(len(msg))

10

4. Members and not in operation in

# str成员运算
msg = 'my name is nash, nash handsome'

print(f"'nick' in msg: {'nick' in msg}")
print(f"'langyigang' not in msg: {'langyigang' not in msg}")
print(f"not 'langyigang' in msg: {not 'langyigang' in msg}")

'nash' in msg: True
'langyigang' not in msg: True
not 'langyigang' in msg: True

5. Remove the blank strip ()

# str移除空白strip()
name = '&&&n ash'

print(f"name.strip('&'): {name.strip('&')}")  # strip()默认为‘ ’,并且不修改原值,新创建空间
print(f"name: {name}")

# strip()应用场景
pwd = input('password: ')  # 用户可能会手抖输入空格
if pwd.strip() == '123':
    print('密码输入成功')

print(f"'*-& nash+'.strip('*-& +'): {'*-& nash+'.strip('*-& +')}")

name.strip('&'): n ash
name: &&&n ash
password: 123
密码输入成功
'*-& nash+'.strip('*-& +'): nash

6. Segmentation split

# str切分split
info = 'nick:male:19'
info_list1 = info.split(':')
info_list2 = info.split(':', 1)

print(f'info_list1:{info_list1}')
print(f'info_list2:{info_list2}')

info_list1:['nick', 'male', '19'] info_list2:['nick', 'male:19']
7. cycle

msg = 'hello nash'

for i in msg:
    print(i)

h e l l o
` n
a
s
h
`

Need to know (****)

 1.lstrip&rstrip
 2.lower&upper
 3.startswith&endswith
 4.rsplit
 5.join
 6.replace
 7.isdigit
`1.lstrip()和rstrip()

# str之lstrip()和rstrip()
name = '&&nash&&'

print(f"nash.lstrip('&'): {name.lstrip('&')}")
print(f"nash.rstrip('&'): {name.rstrip('&')}")

nash.lstrip('&'): nash&& nash.rstrip('&'): &&nash

2.lower () and upper ()

# str之lower()和upper()
name = 'Nash Jin'

print(f"name.upper(): {name.lower()}")
print(f"name.upper(): {name.upper()}")

name.upper(): Nash Jin name.upper(): NASH JIN

3.startswith()和endswith()

str of startswith () and endswith ()

name = 'Nash Jin'

print(f"name.startswith('Nash'): {name.startswith('Nash')}")
print(f"name.endswith('jin'): {name.endswith('jin')}")

name.startswith('Nash'): True name.endswith('jin'): False
4.rsplit ()

# str之rsplit()
info = 'nick:male:19'

print(f"info.rsplit(':', 1): {info.rsplit(':', 1)}")  # 从右开始切割

info.rsplit(':', 1): ['nick:male', '19']

5.join()

lis = [1,2,'19']
print(f"':'.join(lis): {':'.join(lis)}")  # 报错,数字不可和字符串拼接
# str之join()
lis = ['nash', 'male', '18']

print(f"':'.join(lis): {':'.join(lis)}")

':'.join(lis): nash:male:19

6.replace()

# str值replace()
name = 'nash shuai'

print(f"name.replace('shuai','handsome'): {name.replace('shuai','handsome')}")

name.replace('shuai','handsome'): nick handsome
7.isdigit ()

# str值isdigit()
salary = '111'
print(salary.isdigit())  # True

salary = '111.1'
print(salary.isdigit())  # False

True
False

# str之isdigit()应用场景
age = input('age: ')
if age.isdigit():
    age = int(age)

    if age < 18:
        print('小姐姐')
    else:
        print('阿姨好')
else:
    print(f'你的年龄能是这个{age}?')

age: 逗你玩? 你的年龄能是这个逗你玩??

Other operations

 1.find|rfind|index|rindex|count
 2.center|ljust|rjust|zfill
 3.expandtabs
 4.captalize|swapcase|title
 5.is系列
1.find()、rfind()、index()、rindex()、count()

# str之find()、rfind()、index()、rindex()、count()
msg = 'my name is langyigang, langyigang shi sb, hha'

print(f"msg.find('langyigang'): {msg.find('langyigang')}")  # 找不到返回-1
print(f"msg.find('langyigang',0,3): {msg.find('langyigang',0,3)}")
print(f"msg.rfind('langyigang'): {msg.rfind('langyigang')}")  # 找不到返回-1
print(f"msg.index('langyigang'): {msg.index('langyigang')}")  # 找不到报错
print(f"msg.rindex('langyigang'): {msg.rindex('langyigang')}")  # 找不到报错
      

print(f"msg.count('langyigang'): {msg.count('langyigang')}")

msg.find('langyigang'): 11 msg.find('langyigang',0,3): -1 msg.rfind('langyigang'): 17 msg.index('langyigang'): 11 msg.rindex('langyigang'): 17 msg.count('langyigang'): 2
2.center (), light (), rjust (), zfill ()

# str之center()、ljust()、rjust()、zfill()
print(f"'info nash'.center(50,'*'): {'info nash'.center(50,'*')}")
print(f"'info nash'.ljust(50,'*'): {'info nash'.ljust(50,'*')}")
print(f"'info nash'.rjust(50,'*'): {'info nash'.rjust(50,'*')}")
print(f"'info nash'.zfill(50): {'info nash'.zfill(50)}")  # 默认用0填充

'info nash'.center(50,'*'): ********************info nash********************* 'info nash'.ljust(50,'*'): info nash***************************************** 'info nash'.rjust(50,'*'): *****************************************info nash 'info nash'.zfill(50): 00000000000000000000000000000000000000000info nash
3.expandtabs()

# str之expandtabs()
print(f"a\\tb\\tc: %s"%('a\tb\tc\t'))  # 默认制表符8个空格
print(f"'a\\tb\\tc'.expandtabs(32): %s"%('a\tb\tc\t'.expandtabs(32)))

a\tb\tc: a b c 'a\tb\tc'.expandtabs(32): a

4.captalize () swapcase (), title ()

# str之captalize()、swapcase()、title()
name = 'nash handsome sWAPCASE'

print(f"name.capitalize(): {name.capitalize()}")
print(f"name.swapcase(): {name.swapcase()}")  # 大小写互转
print(f"name.title(): {name.title()}")

name.capitalize(): Nash handsome swapcase name.swapcase(): Nash HANDSOME Swapcase name.title(): Nash Handsome Swapcase

5.is digital hierarchy (just to tell you that, in addition to determining whether the digital Chinese digital future use isdigit () to)
 * isdecimal (): check whether the string value contains decimal character, if it returns True, otherwise False.
 * Isdigit (): If the string contains only digit returns True, otherwise False.
 * Isnumeric (): If the string contains only numeric characters, it returns True, otherwise False.

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

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

6.is Other
 * isalnum (): If there is at least one character string and all the characters are letters or numbers returns True, otherwise False.
 * Isalpha (): If there is at least one character string and all the characters are the letters return True, otherwise False.
 * Islower (): If the string contains only at least one of alphanumeric characters, and all of these (case-sensitive) characters are lowercase, returns True, otherwise False.
 * Isspace (): If the string contains only blank, returns True, otherwise return False
 * isupper (): If the string contains at least one case sensitive characters, and all of these (case-sensitive) characters are capital, returns True, otherwise False.
 * Istitle (): If the string is the type of title (see title ()), it returns True, otherwise False.


Stored value or a plurality of values:

A value

Variable or invariable:

Immutable data type

Guess you like

Origin www.cnblogs.com/suren-apan/p/11374825.html