python basic data types and strings

Posted by Canman2005 on Fri, 28 Jan 2022 02:57:22 +0100

1. Variables

definition:
A variable is a box for storing data. We call the data in the box by using the variable box
Naming rules:
Variable names can only contain letters, numbers, and underscores. Variable names can start with letters or underscores, but not numbers;
Variable names cannot contain spaces, but underscores can be used to separate words;
Do not use Python keywords and function names as variable names;
Variable names should be short and descriptive;
Be careful with the lowercase letter l and the capital letter O, as they may be mistaken for the numbers 1 and 0

2. Basic data type

  1. Integer - int
  2. Decimal ----- float
  3. Boolean value - true, false
  4. String ----- string (% s)

3. String

1. Definition:

A string is a string of characters consisting of numbers, letters and underscores.'1223',''12wej,'123_weddww466587''etc.

2. Escape character

3. Long string

(1) '', '', multiple input and output lines are available:

a='''hello
westos'''
print(a)
hello
westos

(2) \ t \ nexample

a1= "hello\nworld"
print(a1)
a2= "hello\tworld"
print(a2)
hello
world
hello	world

4. Format string

(1) Join operator "+"

s = 'hello'
print(s+" westos")
hello westos

(2) Three placeholders

(3) Standardized output

s = 'hello'
a = 123
print('%s %d'%(s,a))
hello 123

(4) Standardized output (automatically match the type of variable)

s = 'hello'
a = 123
print(f"{s} {a}")
hello 123
s = 'hello'
a = 123
b = f'{s} {a}'
print(b)
print(f"{s} {a}")
hello 123
hello 123

(5) str.format()
Example 1:

s = 'i like {},{}'
r = s.format('python',"c")
print(r)
i like python,c

Example 2:

n = 'tom is {0} years old.\n {1} is older'
m = n.format("10","jerry")
print(m)
tom is 10 years old.
 jerry is older

Example 3:

s = 'i like {},{}'
r = s.format('python','c','java')
print(r)
i like python,c

#s. The characters in format () can be greater than the number of brackets in s, but read only the first two and cannot be less than.

Search statistics for Strings

s = "hello.westos.123 "
print(s.find('ll'))
print(s.count('l'))
print(s.split('.'))
li = s.split('.')
print("-".join(li))
2
2
['hello', 'westos', '123 ']
hello-westos-123 

s.find() # string s where the first'll 'appears (0,1,2,3,4...)
s.count # number of 'l' in string s
s.split('.') # put '.' in the string s Split the characters into a list
s.join()
Splicing string, used to connect the elements in the sequence with the specified characters to generate a new string.
Returns a new string generated by concatenating elements in a sequence with a specified character.
The syntax str.join(seq) is to use the symbol of STR to link the original sequence of seq
*The sequence must be a string, otherwise an error is reported

seq = ['1','2','3']
print('-'.join(seq))
1-2-3

example

Example 1:
Enter a string randomly and judge whether it is a palindrome string. No matter ":, space, other characters are the first and second... In turn, which is the same as the penultimate first and second... In turn. True, not False

s = input("please input string: ")
s = s.lower().replace(" ","").replace(",","").replace(":","")
if s == s[::-1]:
    print("true")
else:
    print("Flase")
please input string: ssh ada hss , :
true

#s.lower() converts all characters in the string s to lowercase characters
s.replace(",") converts all spaces in the string to ","
s[::-1] arrange strings s in reverse order

Example 2:
Then five mathematical problems of addition, subtraction and multiplication are generated. After calculation, students enter the calculated answer, and the correct answer is returned to True, and the Error is returned to Error. Finally, the correct rate is counted:

import random
n=0
for i in range(5):
    num1 = random.randint(1,10)
    num2 = random.randint(1,10)
    symbol = random.choice(['+','-','*'])
    print(f'{num1}{symbol}{num2}= ')
    result =eval(f'{num1}{symbol}{num2}')
    sum = int(input ("please input your answer: "))
    if sum == result:
        n+=1
        print("True")
    else:
        print("Error")
hege = (n/5 )*100
print(f'zhunquelvwei: {hege}%')
6+6= 
please input your answer: 12
True
7+10= 
please input your answer: 15
Error
10*10= 
please input your answer: 1
Error
6+1= 
please input your answer: 1
Error
8-1= 
please input your answer: 1
Error
zhunquelvwei: 20.0%
#random.randint(1,10) then generates a number of (1... 10)
  random.choice(['+','-','*'])  Immediately in['+','-','*']Select one
  eval()Calculation function

Example 3:
Randomly input an ip to judge whether it is in the correct format, correctly output IPV4, and error output Nether:

ip = input("please input ipaddr: ")
code = 0
for x in ip.split('.'):
    if not x.isdigit():
        code += 1
    elif not 0 <= int(x) <=255:
        code += 1
    elif len(x) !=1 and int(x[0]) == 0:
        code += 1

if code == 0:
    print("IPV4")
else:
    print("Nether")
please input ipaddr: 172.02.22.22
Nether

Topics: Python