Python__20—字符串

简介: 字符串的定义、查询操作、大小写转换

1字符串的定义

字符串类型是 Python里面最常见的类型。我们可以简单地通过在引号间包含字符的方式创建它。 Python里面单引号和双引号的作用是相同的。字符串是一种直接量或者说是一种标量,这意味着 Python解释器在处理字符串时是把它作为单一值并且不会包含其他 Python类型的。字符串是不可变类型,就是说改变一个字符串的元素需要新建一个新的字符串。字符串是由独立的字符组成的,并且这些字符可以通过切片操作顺序地访问。

2 查询操作

  1. index:查找子串第一次出现,没有会报错

    s='hello,hello'
    print(s.index('lo'))
    #输出3
  2. rindex:查找子串最后一次出现,没有会报错
  3. find:查找子串第一次出现,没有会返回-1
  4. rfind:查找子串最后一次出现,没有会返回-1

测试代码:

s='hello,hello'
print(s.index('lo'))
print(s.find('lol'))
print(s.rfind('lo'))
print(s.rindex('lol'))

测试结果:

tmp5539.png (752×253) (amazonaws.com)

3 大小写转换

  1. 全部转成大写,s.upper()

    a=s.upper()

  2. 全部转成小写,s.lower()

    s='Hello,Python'
    b=s.lower()
    #输出为hello,python
  3. 大小写交换,s.swapcase()
  4. 每个单词首字母大写,其余小写,s.title()
  5. 第一个字符大写,其余小写,s.capitalize()

测试代码:

s='hOllLKk'
a=s.upper()
print(s)
print(a)
s='Hello,Python'
b=s.lower()
print(b)
c=s.swapcase()
print(c)
d=s.title()
print(d)
e=s.capitalize()
print(e)

测试结果:

tmpD563.png (213×224) (amazonaws.com)

相关文章
|
9天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
191 100
|
9天前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
206 99
|
12天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
12天前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
12天前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
23天前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
2月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
213 92
|
2月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
187 0
|
2月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。

推荐镜像

更多