str1+str2
str1*3
len(str)
print('测试' in '测试用户的账号')
print('测试' in '正式用户的账号')
运行结果:
True
False
print('Abc'.find('c')) #存在则返回该字符串的具体位置,如果不存在则返回-1
print('Abc'.find('Z‘))
运行结果:
2
-1
a = "Python学习笔记"
print(a[0])
print(a[-1])
print(a[-2])
print(a[:6]) #左闭右开
print(a[6:]) #左闭右开
运行结果:
P
记
笔
Python
学习笔记
语法:
str.split(str="", num=string.count(str))
print('a,b,c')
print('a,b,c'.split(','))
print('a,b,c'.split(',', 1))
运行结果:
a,b,c
['a', 'b', 'c']
['a', 'b,c']
语法:
str.strip([chars])
print(' a '.strip())#移除字符串两端的空格
print('\na\n'.strip())#移除换行符
print(' a '.rstrip())#移除字符串右端的空格或制表符
print(' a '.lstrip())#移除字符串左端的空格或制表符
print('AaA'.strip('A'))#移除字符A
运行结果:
a
a
a
a
a
语法:
str.replace(old, new, max)
temp_str = 'this is a test'
print(temp_str.replace('is','IS')
print(temp_str)
运行结果:
thIS IS a test
this is a test
语法:
str.isnumeric(): True if 只包含数字;otherwise False。注意:此函数只能用于unicode string
str.isdigit(): True if 只包含数字;otherwise False。
str.isalpha():True if 只包含字母;otherwise False。
str.isalnum():True if 只包含字母或者数字;otherwise False。
import json
str = '{"key": "wwww", "word": "qqqq"}'
j = json.loads(str)
a1 = "([1,2], [3,4], [5,6], [7,8], (9,0))"
a2 = "{1: 'a', 2: 'b'}"
a3 = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
b1 = eval(a1)
b2 = eval(a2)
b3 = eval(a3)
type(b1)
type(b2)
type(b3)
运行结果:
tuple
dict
list
import ast
# 用法与eval一致,并且没有安全性问题
json.dumps
data = {'name':'wjp','age':'22'}
data = json.dumps(data)
print(data1)
print(type(data1))
运行结果:
{"name": "wjp", "age": "22"}
语法:
str.format()
按位置赋值:
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
>>> "{0} {1}".format("hello", "world") # 设置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
按参数赋值:
#按参数赋值
print("网站名:{name}, 地址 {url}".format(name="百度", url="www.baidu.com"))
# 通过字典设置参数
site = {"name": "百度", "url": "www.baidu.com"}
print("网站名:{name}, 地址 {url}".format(**site))
# 通过列表索引设置参数
my_list = ['百度', 'www.baidu.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
输出结果:
网站名:百度, 地址 www.baidu.com
网站名:百度, 地址 www.baidu.com
网站名:百度, 地址 www.baidu.com
语法:
str.startswith(str1, beg = 0, end =len(string))
str = "Hello,Weicome to python";
print str.startswith( 'Hello' );
print str.startswith( 'to', 2, 4 );
print str.startswith( 'Hello', 2, 4 );
运行结果:
True
True
False
语法:
string.title() #将字符串中每个单词的首字母大写
string.upper() # 将字符串中所有字母大写
string.lower() #将字符串中所有字母小写