python-字符串相关操作

字符串的连接

str1+str2

字符串的复制

str1*3

获取字符串的长度(len)

len(str)

字符串的查找

  1. in
print('测试' in '测试用户的账号')
print('测试' in '正式用户的账号')

运行结果:

True
False
  1. find
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
学习笔记

字符串的分隔(split)

语法:

str.split(str="", num=string.count(str))
  • str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
  • num – 分割次数。默认为 -1, 即分隔所有。
print('a,b,c')
print('a,b,c'.split(','))
print('a,b,c'.split(',', 1))

运行结果:

a,b,c
['a', 'b', 'c']
['a', 'b,c']

移除字符(strip)

语法:

str.strip([chars])
  • chars – 移除字符串头尾指定的字符序列。
print(' a '.strip())#移除空格
print('\na\n'.strip())#移除换行符
print('AaA'.strip('A'))#移除字符A

运行结果:

a
a
a

替换字符(replace)

语法:

str.replace(old, new, max)
  • old,必填,旧的字符串
  • new,必填,新的字符串
  • max,选填,最大替换次数,默认全部
    需要注意 replace 不会改变原 string 的内容
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。

字符串类型转化

字符串和JSON类型

str转JSON

  1. json.loads
    json中内部数据需要用双引号来包围,不能使用单引号
import json
str = '{"key": "wwww", "word": "qqqq"}'
j = json.loads(str)
  1. eval
    将字符串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
  1. literal_eval
 import ast
 # 用法与eval一致,并且没有安全性问题

JSON转str

json.dumps

data = {'name':'wjp','age':'22'}
data = json.dumps(data)
print(data1)
print(type(data1))

运行结果:

{"name": "wjp", "age": "22"}
<class 'str'>

字符串的参数化

语法:

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
发布了3 篇原创文章 · 获赞 0 · 访问量 76

猜你喜欢

转载自blog.csdn.net/yqy_19900420/article/details/105075896