1、type() 获取变量类型
print(type('Hello World'))
print(type("Hello World"))
print(type(1))
控制台结果:
<type 'str'>
<type 'str'>
<type 'int'>
2、int() str() 变量类型的转化
num=1
string='1'
num2=int(string)
print(num+num2)
可以看到,空格也会占一个长度。
3、len() 得到字符串的长度
print(len('caohui'))
print(len('cao hui'))
控制台输出:
6
7
4、replace() 字符串的替换
phoneNumber = '1386-666-0006'
hidingNumber = phoneNumber.replace(phoneNumber[:9],'*'*9)
print (hidingNumber)
控制台输出:
*********0006
5、find() 找到字符串某个字段在字符串中的第一个起始位置
phoneNumber = '000123456789123000'
print(phoneNumber.find('123'))
search='168'
num_a = '1386-168-0006'
num_b = '1681-222-0006'
print(search +' is to '+str(num_a.find(search))+'to'+str(num_a.find(search)+len(search))+' of num_a')
print(search +' is to '+str(num_b.find(search))+'to'+str(num_b.find(search)+len(search))+' of num_b')
第一组输出:
3
第二组输出:
168 is to 5to8 of num_a
168 is to 0to3 of num_b
6、format() 字符串格式化符,实现“填空”输出
print('{} a word she can get what she {} for.'.format('With','came'))
print('{preposition} a word she can get what she {verb} for.'.format(preposition='With',verb='came'))
print('{0} a word she can get what she {1} for.'.format('With','came'))
控制台输出:
With a word she can get what she came for.
With a word she can get what she came for.
With a word she can get what she came for.
7、sum()
num=[1,2,3]
print(sum(num))
控制台输出:
6
8、append()
添加列表元素
9、range()
表示一个范围,经常运用于for循环
10、randrange() 需要先import random
import random
for num in range(1,4):
print(random.randrange(1,7))
控制台输出:(随机的,每次的输出可能不一致)
6
1
6