Built-in Methods for Numeric Types (int and float)
The int() and float() functions are used for type creation and conversion.
# Type definition
age = 10 # Equivalent to age = int(10)
salary = 3000.3 # Equivalent to salary = float(3000.3)
# Type conversion
s = '123'
res = int(s) # Converts string of integers to int
print(res, type(res)) # Output: (123, <class 'int'>)
# Error demonstration
# int('12.3') # ValueError: invalid literal for int() with base 10: '12.3'
# Base conversion
print(bin(3)) # Decimal to binary: '0b11'
print(oct(9)) # Decimal to octal: '0o11'
print(hex(17)) # Decimal to hexadecimal: '0x11'
# Convert from other bases to decimal
print(int('0b11', 2)) # Output: 3
print(int('0o11', 8)) # Output: 9
print(int('0x11', 16)) # Output: 17
# Float conversion
val = '12.3'
result = float(val)
print(result, type(result)) # Output: (12.3, <class 'float'>)
Numeric types primarily support mathematical and comparison operations and do not have many built-in methods beyond these functions.
String Data Type
String literals can be created using single quotes, double quotes, or triple quotes.
name_1 = 'jason'
name_2 = "lili"
name_3 = """ricky"""
Type Conversion
The str() function can convert any data type to a string.
print(type(str([1, 2, 3]))) # list -> str
print(type(str({'name': 'jaswe', 'age': 18}))) # dict -> str
print(type(str({1, 2, 3}))) # set -> str
print(type(str((1, 2, 3)))) # tuple -> str
Fundamental Operasions
text = 'hello python!'
# 1. Indexing
print(text[6]) # 'p' (forward indexing)
print(text[-4]) # 'h' (reverse indexing)
# text[0] = 'H' # Error: strings are immutable
# 2. Slicing
print(text[0:9]) # 'hello pyt' (slice from 0 to 8)
print(text[0:9:2]) # 'hlopt' (step of 2)
print(text[::-1]) # '!nohtyp olleh' (reverse)
# 3. Length
print(len(text)) # 13
# 4. Membership tests
print('hello' in text) # True
print('tony' not in text) # True
Key String Methods
1. strip(), lstrip(), rstrip()
str_1 = '###Erfd###'
print(str_1.strip('#')) # 'Erfd' (both sides)
print(str_1.lstrip('#')) # 'Erfd###' (left side)
print(str_1.rstrip('#')) # '###Erfd' (right side)
2. lower(), upper()
str_2 = 'saEFDfef'
print(str_2.lower()) # 'saefdfef'
print(str_2.upper()) # 'SAEFDFEF'
3. startswith(), endswith()
str_3 = 'tony jam'
print(str_3.startswith('t')) # True
print(str_3.endswith('t')) # False
4. format()
# Keyword arguments
str_4 = 'name:{name}, age:{age}'.format(age=18, name='sfv')
print(str_4) # 'name:sfv, age:18'
# Positional arguments
str_5 = 'name:{}, age:{}'.format('asdf', 12)
print(str_5) # 'name:asdf, age:12'
# Indexed arguments
str_6 = 'name:{1}, age:{0}'.format(12, 'dsdf')
print(str_6) # 'name:dsdf, age:12'
5. split(), rsplit()
path = 'c:/sdw/ds/dw/ac/sd.txt'
print(path.split('/', 1)) # ['c:', 'sdw/ds/dw/ac/sd.txt'] (left to right)
print(path.rsplit('/', 1)) # ['c:/sdw/ds/dw/ac', 'sd.txt'] (right to left)
6. join()
print('#'.join('sefdgs')) # 's#e#f#d#g#s'
print('|'.join(['tony', '18', 'read'])) # 'tony|18|read'
7. replace()
str_7 = 'my name is tony, my age is 18!'
print(str_7.replace('18', '34')) # 'my name is tony, my age is 34!'
print(str_7.replace('my', 'MY', 1)) # 'MY name is tony, my age is 18!'
8. isdigit()
print('235235'.isdigit()) # True
print('235223sf35'.isdigit()) # False
Additional String Methods
1. find() and rfind()
sample = 'tonr asr dfeei sccof'
print(sample.find('o', 0, 13)) # 1 (returns index, -1 if not found)
# .index() is similar but raises ValueError if not found
2. count()
print(sample.count('o')) # 2
3. center(), ljust(), rjust(), zfill()
name = 'sdacd'
print(name.center(30, '-')) # '------------sdacd------------'
print(name.rjust(30, '@')) # '@@@@@@@@@@@@@@@@@@@@@@@sdacd'
print(name.ljust(30, '#')) # 'sdacd#########################'
print(name.zfill(50)) # '000000000000000000000000000000000000000000sdacd'
4. expandtabs()
print('tony\thello') # 'tony hello' (\t expands to tab)
5. capitalize(), swapcase(), title()
example = 'hello xIanG mo yu'
print(example.capitalize()) # 'Hello xiang mo yu'
print(example.swapcase()) # 'HELLO XiANg MO YU'
print(example.title()) # 'Hello Xiang Mo Yu'
6. Numeric checks
# Different methods for checking numeric characters
num1 = '4' # ASCII digit
num2 = '四' # Chinese numeral
num3 = 'Ⅳ' # Roman numeral
print(num1.isdigit()) # True
print(num2.isdigit()) # False
print(num3.isdigit()) # False
print(num1.isdecimal()) # True
print(num2.isdecimal()) # False
print(num3.isdecimal()) # False
print(num1.isnumeric()) # True
print(num2.isnumeric()) # True
print(num3.isnumeric()) # True
List Data Type
Lists are defined within square brackets and can contain elements of any data type.
list_1 = [1, 'a', [1, 2]] # Equivalent to list([1, 'a', [1, 2]])
Type Conversion
Any iterable can be converted to a list using list().
print(list('wdad')) # ['w', 'd', 'a', 'd']
print(list([1, 2, 3])) # [1, 2, 3]
print(list({'name': 'jason', 'age': 18})) # ['name', 'age']
print(list((1, 2, 3))) # [1, 2, 3]
print(list({1, 2, 3, 4})) # [1, 2, 3, 4]
List Operations
1. Indexing and Assignment
friends = ['tony', 'jason', 'tom', 4, 5]
print(friends[0]) # 'tony'
print(friends[-1]) # 5
friends[1] = 'martthow' # Lists are mutable
print(friends) # ['tony', 'martthow', 'tom', 4, 5]
2. Slicing
print(friends[0:4]) # ['tony', 'martthow', 'tom', 4]
print(friends[0:4:2]) # ['tony', 'tom'] (step of 2)
3. Length
print(len(friends)) # 5
4. Membership tests
print('tony' in friends) # True
print('xxx' not in friends) # True
5. Adding Elements
# append() adds to the end
list_a = ['a', 'b', 'c']
list_a.append('d')
print(list_a) # ['a', 'b', 'c', 'd']
# extend() adds multiple elements
list_a.extend(['e', 'f'])
print(list_a) # ['a', 'b', 'c', 'd', 'e', 'f']
# insert() adds at specific position
list_a.insert(0, 'first')
print(list_a) # ['first', 'a', 'b', 'c', 'd', 'e', 'f']
6. Removing Elmeents
# del statement
list_b = [11, 22, 33, 44]
del list_b[2]
print(list_b) # [11, 22, 44]
# pop() removes and returns element
list_c = [11, 22, 33, 22, 44]
removed = list_c.pop()
print(removed) # 44
print(list_c) # [11, 22, 33, 22]
removed = list_c.pop(1)
print(removed) # 22
print(list_c) # [11, 33, 22]
# remove() deletes by value
list_d = [11, 22, 33, 22, 44]
list_d.remove(22) # Removes first occurrence
print(list_d) # [11, 33, 22, 44]
7. reverse()
list_e = [11, 22, 33, 44]
list_e.reverse()
print(list_e) # [44, 33, 22, 11]
8. sort()
list_f = [11, 22, 3, 42, 7, 55]
list_f.sort()
print(list_f) # [3, 7, 11, 22, 42, 55] (ascending)
list_g = [11, 22, 3, 42, 7, 55]
list_g.sort(reverse=True)
print(list_g) # [55, 42, 22, 11, 7, 3] (descending)
9. Iteration
for item in friends:
print(item)
Lists can be compared lexicographically, and sorting works for homogeneous lists of comparable elements.