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)

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

猜你喜欢

转载自www.cnblogs.com/liudemeng/p/12171043.html