Python数据类型字符串

字符串

字符串是Python中比较常用的数据类型。我们可以使用引号('或者")创建字符串。

string = "hello world"
字符串是数组

Python中的字符串表示Unicode字符的字节数组。使用方括号[]可以访问字符串的元素。

字符串是字符的有序集合,可以通过其位置来获得具体的元素。在 python 中,字符串中的字符是通过索引来提取的,索引从 0 开始。

python 可以取负值,表示从末尾提取,最后一个为 -1,倒数第二个为 -2,即程序认为可以从结束处反向计数。

示例代码:

string = "hello world"
print(string[0])
print(string[-5:-2])
print(string[::-1])

注意:[start:stop:step]类似于range()函数,顾头不顾尾。

获取字符串的长度

len()函数获取字符串的长度,len()函数数据类型我们会经常使用。

示例代码:

string = "hello python"
print(string)
print("字符串的长度是", len(string))

字符串的常用方法

由于字符串的方法有很多,本片文章只介绍常用的方法。

strip()删除开头或结尾空白字符
string = '   helllo   '
print(string.strip())
count()获取某个字符在字符串出现的次数
string = "hello python"
print("字符o的次数是:",string.count('o'))
find()找到字符返回下标,多个时返回第一个,不存在的字符返回-1
string = "hello python"
print(string.find('n'))
print(string.find('a')) # 打印-1
index()找到字符返回下标,多个时返回第一个,不存在直接报错
string = "hello python"
print(string.index('l'))
print(string.index('a')) # 直接报错
replace(oldstr,newstr)字符串替换
string = "hello python"
new_str = string.replace('p',"P")
print(new_str)
format()字符串格式化
string = 'hello{}'
new_str = string.format('你好')
print(new_str)
startswith() endswith() 判断字符开头和结尾
string = "hello Python"
print(string.startswith('h'))
print(string.endswith('n'))
split()字符串的分割
string = "hello world"
print(string.split(" "))

注意:分割字符串返回是一个列表,列表里面就是分割的字符串。

join()连接字符串
string = "hello"
new_str = '你好'.join(string)
print(new_str)
字符串相加,字符串相乘
str1 = "hello"
str2 = "world"
new_str1 = str1 + str2
new_str2 = str1 * 3
print(new_str1)
print(new_str2)

可以发现:字符串和字符串相加只是拼接字符串,而字符串和数字相乘则是复制三个相同的字符串。

字符串的遍历

推荐使用for循环,while循环一般作为死循环使用。
代码示例:

string = "hello world"
for i in string:
    print(i)

以上只介绍了字符串的部分方法,如果觉得本文可以麻烦点个在看。你的支持是我最大的动力。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值