table of Contents
Attributes
Code | Features | Remark |
---|---|---|
len(s) |
String length | |
type(s).__name__ |
type name | If the string is outputstr |
s[0],s[1],s[-1] |
Take the string 1, 2, and the last character | |
s.find('x') |
Determine the location of the development of character in the string | |
s.count('x') |
Specified character (string) appeared several times in s | |
s.index('1') |
Specify the location of the character (string) for the first time in s (default) |
Judge
Code | Features | Remark |
---|---|---|
s.isalpha() |
Are all letters, and at least one character | |
s.isdigit() |
It is all digital, and there is at least one character | |
s.isspace() |
Whether all whitespace characters, and there is at least one character | |
s.islower() |
Whether all lowercase letters | |
s.isupper() |
Whether the letter is upper case | |
s.istitle() |
Whether it is capitalized | |
s.startswith('a') |
The first letter of verification | |
s.endswith('a') |
Verify the last letter | |
'xyz' in s |
If they contain characters developed (string) |
format
operating | Code | Remark |
---|---|---|
All capital letters | s.upper() |
|
All lowercase letters | s.lower() |
|
Capitalized | s.capitalize() |
|
Invert case | s.swapcase() |
The original uppercase letters to lowercase, and vice versa |
Formatted output
# 整数
s = 1
print('整数示例 %d'%s)
Output:
整数示例 1
# 小数
s = 1.2345
print('小数示例 %5.2f'%s) # 整数保留5位,小数保留2位
Output:
小数示例 1.23
# 百分比
s = 0.058
print('百分比示例 %5.2f%%'%(s*100))
Output:
百分比示例 5.80%
deformation
Overturn
s = '12345'
s[::-1]
Output:
'54321'
splice
s1 = 'abc'
s2 = '123'
s1+s2
Output:
'abc123'
'.'.join(s1)
'.'.join([s1,s2])
s1.join(s2)
Output:
'a.b.c'
'abc.123'
'1abc2abc3'
Split
s = 'I am Groot'
s.split(' ') #此处以空格作为分隔符
s.partition(' ')
Output:
['I', 'am', 'Groot']
('I', ' ', 'am Groot')
repeat
s = 'abc'
s*3
Output:
'abcabcabc'
filling
s = '12'
s.zfill(5)
Output:
'00012'
s = 'begin'
s.center(30,'*')
Output:
'************begin*************'
Wash
White spaces
s.strip() # 去除两端的空格
s.rstrip() # 去除右侧的空格
s.lstrip() # 去除左侧的空格
Letter substitutions
One replacement
s = 'this is a test'
s.replace('t','T')
Output:
'This is a TesT'
Many-to-replace
# 多个字符串替换成单个字符串
import re
re.sub('t|T|s','H',s)
tab characters are replaced by eight spaces:s.expandtabs
Character matches
Whether it contains a character (string)
'x' in s
'xyz' in s
If it contains a few characters (string) of
items_list = re.findall('(字符串1|字符串2|字符串3)',s)
# 如果匹配到了,那么item_list长度>0
if len(items_list)>0:
print('匹配到相关字符')
Extraction according to the rules of
usage of regular expressions refer
Details can be found the most complete encyclopedia of common regular expressions
coding
Reference to this article