Python Basic Data Types and Operations Tutorial
This tutorial introduces Python's fundamental data types—including strings, numbers, lists, tuples, and dictionaries—explains their characteristics, common built‑in functions, and demonstrates practical code examples for manipulation, formatting, and conversion.
String Type
Strings are sequences composed of one or more characters.
Strings are usually delimited by single quotes, double quotes, triple single quotes, or triple double quotes.
Escape Characters
Raw strings (prefix r ) disable escape processing.
\n newline
\b backspace
\r carriage return
\t tab
\? a question mark
Practice Code
str1 = "Hello World !"
str2 = ''' ssss
sssssss'''
print(str1,str2)
str3 = "你好 中国"
print(str3)
# slicing
str4 = "hello I am zhangsan!"
print(str4[8])
print(str4[:5]) # stop index is exclusive, start index 0 can be omitted.
print(str4[5:]) # start index is inclusive, start index 0 can be omitted.
print(str4[-10:-1])
# concatenation
str5 = "Hello"
str6 = "World !"
str7 = "123"
print(str5 + ' ' + str6 + str7) # string concatenation cannot mix with int
# string formatting
name = "zzzz"
age = 123
newage = str(age) # str() converts to string
print(type(newage))
print("my name is %s, my age is %d" %(name,age)) # %s for string, %d for integer
msg = "my name is {0}, my age is {1}".format(name,age)
print(msg)
# escape characters
new1 = r"abc \n cba"
print(new1)Built‑in String Functions
capitalize()
count()
decode()
encode()
endswith()
startswith()
find()
index()
isalpha()
lstrip()/rstrip()/strip()
replace()
upper()
split()
reponse = " abcd123 45abcd "
print(reponse.capitalize()) # capitalize first character
print(reponse.count('b',2,len(reponse))) # count occurrences between positions
print(reponse.encode(encoding="UTF-8")) # encode string
newreponse = reponse.encode(encoding="UTF-8")
print(newreponse.decode(encoding="UTF-8")) # decode string
print(reponse.startswith("b")) # check start
print(reponse.endswith("c")) # check end
print(reponse.find("ac")) # find substring, returns -1 if not found
print(reponse.index('b')) # index of first occurrence
print(reponse.isalpha()) # all alphabetic?
print(reponse.lstrip()) # left strip spaces
print(reponse.rstrip()) # right strip spaces
print(reponse.strip()) # strip both sides
print(reponse.replace(" ","")) # replace double space
print(reponse.upper()) # to uppercase
print(reponse.split(" ")) # split by double spaceNumber Type
Classification
Integer
Boolean
Floating‑point
Complex
Operators
+ - * / % arithmetic operators; > = < >= <= == comparison operators.
Practice Code
age = 45 # positive integer
memory = -100 # negative integer
a = 0x768A # hexadecimal integer
print("my age is : %d, my memory is : %d" % (age,memory))
print(a)
a = True
b = False
print(int(a),int(b))
c = 1.2
d = 2.4
print(c,type(d))
a = 123
b = 456
print("a + b = " + str(a+b) )
print("a - b = " + str(a-b))
print("a * b = " + str(a*b))
print("a / b = " + str(a /b) )
print("a > b " + str(a > b))
print("a < b " + str(aList Type (list)
Built‑in Functions
append()
count()
extend()
index()
insert()
pop()
remove()
reverse()
Practice Code
## definition
a = []
print(type(a))
numlist = [1,2,3,4,5,6]
strlist = ["a","b","c","d"]
print(numlist,strlist)
## access elements
print(numlist[3],strlist[2])
print(numlist[:5])
print(len(numlist))
## application
ipAddress = [r"192.158.0.1",r"192.168.0.2"]
print(ipAddress)
## iteration
for ip in ipAddress:
print(ip)
# built‑in functions
testHosts = ["aa","bb","cc","dd"]
t1 = ["dd","cc"]
testHosts.append("EE") # append at end
print(testHosts.count('bb')) # count occurrences
print(testHosts.extend(t1)) # extend list
print(testHosts.index("EE")) # get index of element
testHosts.insert(5,"DD") # insert at position 5
print(testHosts)
print(testHosts.pop(2)) # pop by index
print(testHosts)
testHosts.remove("EE") ## remove element
print(testHosts)
testHosts.reverse() # reverse list
print(testHosts)Tuple Type
Elements in a tuple are immutable.
# definition
a = ()
print(type(a))
a = (1,2,3,4,5)
b = ("aa","bb","cc")
print(a,b)
# usage
test = ("java","tomcat","springboot")
print(test[1])
print(test[:2])
test1 = ([1,2,3],"aa")
print(test1)
test1[0].append(123)
print(test1)Dictionary Type
Key/value mapping.
Built‑in Functions
clear()
copy()
get()
items()
keys()
update()
pop()
values()
Practice Code
# definition
a = {}
print(type(a))
myinfo = {"name":"zhangsan","age":45}
print(myinfo)
print(myinfo['name'])
myinfo["job"] = "devops1" # add or modify
print(myinfo)
# built‑in functions
myinfo = {"name":"zhangsan","age":45}
#print(myinfo.clear()) # clear dictionary
print(myinfo)
data1 = myinfo.copy() # shallow copy
print(data1)
data1["name"] = "lisi"
print(data1)
print(myinfo)
print(myinfo.get("name")) # get value by key
print(myinfo.items()) # view items as (key, value) tuples
print(type(myinfo.items()))
print(myinfo.keys()) # all keys
print(myinfo.values()) # all values
print(myinfo.pop("name")) # remove by key
print(myinfo)Practical Example 1 – Python Formatted Output
## %
name = "zhangsan"
age = 45
print("my name is : %s , my age is %s" % (name,str(age)))
## format
name = "lisi"
age = 34
print("my name is {0}, my age is {1}".format(name,age))
## multi‑line title
info = """
name = {0}
age = {1}
high = {2}
jobs = {3}
address = {4}
"""
print("---------------------")
print(info.format("zhangsan",24,178,"PythonDeveloper","Beijing"))
print("---------------------")Practical Example 2 – List CRUD Operations
## append
## remove pop
students = ["zhangsan","lisi","wangwu"]
## add a student
newStudent = "aa"
students.append(newStudent)
print("class students is : %s " %(students,))
## merge classes
twoStudents = ["cc","dd","ee"]
students.extend(twoStudents)
print("class students is : %s " %(students,))
## transfer class
moveStudent = "wangwu"
students.remove(moveStudent)
print("class students is : %s " %(students,))
## update
studentName = "zhangsanfeng"
stuindex = students.index("zhangsan")
students[stuindex] = studentName
print("class students is : %s " %(students,))Practical Example 3 – Convert JSON to Dictionary
import json
## dict -> json
myinfo = {"name":"zhangsan","age":100}
jsonInfo = json.dumps(myinfo)
print(type(jsonInfo))
## json -> dict
dictInfo = json.loads(jsonInfo)
print(type(dictInfo))
print(dictInfo['age'])
## raw json string
a = '{"name":"zhangsan"}'
print(json.loads(a))DevOps Cloud Academy
Exploring industry DevOps practices and technical expertise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.