Python basic knowledge data type string operation if statement is not usage for loop while loop

Source: Internet
Author: User

Python all data types are objects
print(type(123))print(type(4545.666))print(type(1323.))print(type(‘adbn‘))
<class ‘int‘><class ‘float‘><class ‘float‘><class ‘str‘>
All data types are objects
print(type([1,2,2,3,4,5,56,‘a‘,‘b‘]))print(type((1,‘xddfsdfd‘)))print(type(set([‘s‘,‘rff‘,‘dd‘])))print(type({‘a‘: 1, ‘b‘: 2}))
<class ‘list‘><class ‘tuple‘><class ‘set‘><class ‘dict‘>
function is also an object variable also available in Chinese
def func(a,b,c):    print(a,b,c)print(type(func))啊 = funcprint(type(啊))a = funcprint(type(a))
<class ‘function‘><class ‘function‘><class ‘function‘>
The type of string is the module
import stringprint(type(string))
<class ‘module‘>
A class that is not instantiated is called a type instantiation object called Class
class MyClass(object) :        passprint(type(MyClass))my_class = MyClass()print(type(my_class))
<class ‘type‘><class ‘__main__.MyClass‘>
Exception handling, variables must be defined before they are used
try:    x = 100    print(x)except NameError:    print("NameError: ‘x‘ is not define")
Common string processing string cannot be changed
import strings = ‘abc‘s[0] = ‘sd‘
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-1-ce449e8a2e6b> in <module>()      2       3 s = ‘abc‘----> 4 s[0] = ‘sd‘TypeError: ‘str‘ object does not support item assignment
Remove whitespace action
import strings = ‘  hjh 黄金进口件 你看见画江湖 mjjkj ‘# 去除左右空格print(s.strip())# 去除左边空格print(s.lstrip())# 去除右边空格print(s.rstrip())# 输出原来的字符串print(s)
hjh 黄金进口件 你看见画江湖 mjjkjhjh 黄金进口件 你看见画江湖 mjjkj   hjh 黄金进口件 你看见画江湖 mjjkj  
Connection string
s1 = ‘abc‘s2 = ‘def‘print(s1 + "\n" + s2)
abcdef
Uppercase and lowercase conversions
s = ‘abc def‘print(s)#把所有字符变成大写print(s.upper())# 把所有字符变大写后变回去print(s.upper().lower())# 首字母大写print(s.capitalize())
abc defABC DEFabc defAbc def
Location comparison
s1 = ‘abcdefg‘s2 = ‘lalalal‘print(s1.index(‘f‘))print(s1.index(‘fg‘))print(s2.index(‘alal‘))# 找不到时会报错需要异常处理try:    print(s1.index(‘jjj‘))except ValueError:    pass
551
Comparing strings
s1 = ‘ddd‘s2 = ‘sss‘print(s1 == s2)print(s1 < s2)print(s1 > s2)
FalseTrueFalse
String length
601
Empty string differs from None
s = ‘‘if s is None:    print(‘None‘)p = Noneif p is None:    print(‘p is None‘)
p is None
Segmentation of strings
s = ‘abc,def,ghi‘d = ‘abc..def..ghi‘splitted = s.split(‘,‘)print(type(splitted))print(splitted)# 可以按照任意分隔符切分d1 = d.split(‘..‘)print(type(d1))print(d1)# 可以按行分割s1 = """ddddddggggghhhyyyyyjj"""# 方法一按照换行符分割print(s1.split(‘\n‘))# 方法二直接使用按行分割的方法print(s1.splitlines())#区别 按照换行符分割的特点是数量 只与换行符有关 而且使用方法不会捕捉到最后一个换行符
<class ‘list‘>[‘abc‘, ‘def‘, ‘ghi‘]<class ‘list‘>[‘abc‘, ‘def‘, ‘ghi‘][‘ddd‘, ‘dddgg‘, ‘ggg‘, ‘hhh‘, ‘yy‘, ‘yyy‘, ‘jj‘, ‘‘][‘ddd‘, ‘dddgg‘, ‘ggg‘, ‘hhh‘, ‘yy‘, ‘yyy‘, ‘jj‘]
Connection of strings
s = [‘ddd‘, ‘dddgg‘, ‘ggg‘, ‘hhh‘, ‘yy‘, ‘yyy‘, ‘jj‘]# 使用空字符作为连接字符print(‘‘.join(s))print(‘\n‘)# 使用换行符作为连接对象print(‘\n‘.join(s))print(‘\n‘)# 使用短线作为连接对象print(‘-‘.join(s))
ddddddggggghhhyyyyyjjddddddggggghhhyyyyyjjddd-dddgg-ggg-hhh-yy-yyy-jj
Common judgments
s = ‘assddf‘# 判断是不是以字符a开头print(s.startswith(‘a‘))# 判断是不是以字符ass开头print(s.startswith(‘ass‘))# 判断是不是以字母s开头print(s.startswith(‘s‘))# 判断以...结尾print(s.endswith(‘ddf‘))# 判断是不是数字字母的组合print(‘12333hjhjhdas‘.isalnum())print(‘\t212133kjhjdashkjdas‘.isalnum())# 判断是不是纯字母的形式print(‘sjas‘.isalpha())# 判断是不是数字print(‘asada‘.isdigit())# 判断是不是所有单词以大写字母开头print(‘Hello World‘.istitle())
TrueTrueFalseTrueTrueFalseTrueFalseTrue
Convert numeric strings to each other
print(str(5))print(str(5.))print(str(55645.545))print(str(-5454.5454))print(int(‘5656‘))print(float(‘5454.544‘))print(float(‘555.566‘))# 可以指定转换类型  默认是10进制print(int(‘1010101010001‘, 2))print(int(‘abcdef‘, 16))print(int(‘77421‘, 8))
55.055645.545-5454.545456565454.544555.56654571125937532529
String characters convert to each other
s = ‘asdf‘l = list(s)print(l)
[‘a‘, ‘s‘, ‘d‘, ‘f‘]
If judgment
a = 100b = 200c = 300if a == 100:    print(a)elif b == 200:    print(b)else:    print(c)
100
The judgment of None
x = Noneif x is None :    print(‘None‘)else:    print(‘not None‘)
None
For loop
# range(开始数,结束数,间隔)for i in range(0, 30, 5):    print(i)# 不指定间隔时间隔是1for i in range(5,10):    print (i)
051015202556789
While loop
s = 0i = 1while i <= 100:    s += i    i += 1print(s)
5050
About pass and continue and the use of break
for i in range(0, 100):    if i < 10:        pass    elif i < 30:        continue    elif i < 35:        print(i)    else:        break
Definition of a function
def func_name(arg1, arg2):    print(arg1, arg2)    return arg1, arg2def func_name0(arg1, arg2):    print(arg1, arg2)    return arg1 + arg2r = func_name(1, 2)print(type(r))# 可以说是是一个listprint(r[0],r[1])print(func_name0(3, 5))
1 2<class ‘tuple‘>1 23 58
function can specify a default value at the parameter position
def func(x, y = 500):    return x + y# 当调用时有全部参数时就会使用参数print(func(100,800))# 当有一个值未指定时,就会使用默认值print(func(100))
900600
Function arguments can be reversed position
def func(x, y = 500):    print(‘x = ‘, x)    print(‘y = ‘, y)    return x + yprint(func(100))print(func(y = 300, x = 200))print(func(x = 400))
x =  100y =  500600x =  200y =  300500x =  400y =  500900
Variable parameters of a function
# 表示从第一个参数开始所有参数都放到数组里去def func(name, *numbers):    # 类型是只读数组原族    print(type(numbers))    print(numbers)    return ‘Done‘func(‘Tom‘, 1, 2, 3, 4)
<class ‘tuple‘>(1, 2, 3, 4)‘Done‘

Python basic knowledge data type string operation if statement is not usage for loop while loop

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.