Python教程-String 字符串使用教程

位置:首页>文章>详情   分类: 教程分享 > Python教程   阅读(9095)   2023-03-28 11:29:14

python

Python 语言中的String

在Python中,String代指以下特点:
  • 代表Unicode字符的字节数组
  • 用单引号或双引号引起来
  • 无限长度

Python 中 String 字符串定义方式

$title(单行文字的定义方法)
str = 'hello world'
 
str = "hello world"
一个多行字符串使用三个单引号或三个双引号创建:
$title(多行文字的定义方法)
str = '''Say hello
        to python
        programming'''
 
str = """Say hello
        to python
        programming"""

Python没有字符数据类型,单个字符就是长度为1的字符串。

python String 字符串截取 /分割

通过使用slice语法,我们可以获得一组字符。索引从零开始。

str[m:n] 从位置2(包括)到5(不包括)返回字符串。
 

$title(截取字符串索引2到5部分)
str = 'hello world'
 
print(str[2:5]) # llo

负切片将从末尾返回子字符串:
$title(截取字符串从索引-5到-2部分)
str = 'hello world'
 
print(str[-5:-2])   # wor
str[-m:-n] 将字符串从位置-5(不包括)返回到-2(包括)。

python中的字符串数组

在python中,字符串表现为数组。方括号可用于访问字符串的元素
 

tr = 'hello world'
 
print(str[0])   # h
print(str[1])   # e
print(str[2])   # l
 
print(str[20])  # 错误的索引: string index out of range

python字符串长度计算

 

len()函数返回字符串的长度:

str = 'hello world'
 
print(len(str)) # 11

python字符串格式化

要在python中格式化s字符串,请{ }在所需位置在字符串中使用占位符。将参数传递给format()函数以使用值格式化字符串。
我们可以在占位符中传递参数位置(从零开始)。
 

age = 36
name = 'Lokesh'
 
txt = "My name is {} and my age is {}"
 
print(txt.format(name, age))    # My name is Lokesh and my age is 36
 
txt = "My age is {1} and the name is {0}"
 
print(txt.format(name, age))    # My age is 36 and the name is Lokesh

python字符串其他内置函数方法

1. 1.capitalize() 大写转换

它返回一个字符串,其中给定字符串的第一个字符被转换为大写。当第一个字符为非字母时,它将返回相同的字符串。
name = 'lokesh gupta'
 
print( name.capitalize() )  # Lokesh gupta
 
txt = '38 yrs old lokesh gupta'
 
print( txt.capitalize() )   # 38 yrs old lokesh gupta

1.2. casefold()小写转换

它返回一个字符串,其中所有字符均为给定字符串的小写字母。
 

txt = 'My Name is Lokesh Gupta'
 
print( txt.casefold() ) # my name is lokesh gupta

1.3. center()中间对其方法

使用指定的字符(默认为空格)作为填充字符,使字符串居中对齐。
在给定的示例中,输出总共需要20个字符,而“ hello world”位于其中。
txt = "hello world"
 
x = txt.center(20)
 
print(x)    # '    hello world     '

1.4. count() 计算

它返回指定值出现在字符串中的次数。它有两种形式:
  • count(value) - value to search for in the string.
    count(value, start, end) - value to search for in the string, where search starts fromstart position till end position.
txt = "hello world"
 
print( txt.count("o") )         # 2
 
print( txt.count("o", 4, 7) )   # 1

1.5. encode() 编码
它使用指定的编码对字符串进行编码。如果未指定编码,UTF-8将使用。
txt = "My name is åmber"
 
x = txt.encode()
 
print(x)    # b'My name is \xc3\xa5mber'

1.6. endswith() 判断字符串结尾

rue如果字符串以指定值结尾,则返回,否则返回False

txt = "hello world"
 
print( txt.endswith("world") )      # True
 
print( txt.endswith("planet") )     # False
 

1.7. expandtabs()

它将制表符大小设置为指定的空格数。
txt = "hello\tworld"
 
print( txt.expandtabs(2) )      # 'hello world'
 
print( txt.expandtabs(4) )      # 'hello   world'
 
print( txt.expandtabs(16) )     # 'hello           world'
 

1.8. find() 字符串查找

它查找指定值的第一次出现。-1如果字符串中没有指定的值,它将返回。
find()index()方法相同,唯一的区别是,index()如果找不到该值,该方法将引发异常。
txt = "My name is Lokesh Gupta"
 
x = txt.find("e")
 
print(x)        # 6

1.9. format()格式化

它格式化指定的字符串,并在字符串的占位符内插入参数值。
age = 36
name = 'Lokesh'
 
txt = "My name is {} and my age is {}"
 
print( txt.format(name, age) )  # My name is Lokesh and my age is 36
 

1.10. format_map()

它用于返回字典键的值,以格式化带有命名占位符的字符串。
params = {'name':'Lokesh Gupta', 'age':'38'} 
 
txt = "My name is {name} and age is {age}"
 
x = txt.format_map(params)
 
print(x)        # My name is Lokesh Gupta and age is 38
 

1.11. index() 索引

  • 它在给定的字符串中查找指定值的第一次出现。
  • 如果找不到要搜索的值,则会引发异常。
txt = "My name is Lokesh Gupta"
 
x = txt.index("e")
 
print(x)        # 6
 
x = txt.index("z")  # ValueError: substring not found

1.12. isalnum()

它检查字母数字字符串。True如果所有字符都是字母数字,即字母(a-zA-Z)和数字,它将返回(0-9)
print("LokeshGupta".isalnum())      # True
 
print("Lokesh Gupta".isalnum())     # False - Contains space

1.13. isalpha()

True如果所有字符都是字母,则返回它,即字母(a-zA-Z)
 

print("LokeshGupta".isalpha())          # True
 
print("Lokesh Gupta".isalpha())         # False - Contains space
 
print("LokeshGupta38".isalpha())        # False - Contains number

1.14. isdecimal()

如果所有字符均为小数(0-9),则返回代码。否则返回False
print("LokeshGupta".isdecimal())    # False
 
print("12345".isdecimal())          # True
 
print("123.45".isdecimal())         # False - Contains 'point'
 
print("1234 5678".isdecimal())      # False - Contains space


 
标签: python
地址:https://www.leftso.com/article/759.html

相关阅读

Python简介​Python是一种流行的编程语言,由Guido van Rossum创建,并于1991年发布
前言在Python(或任何其他编程语言)中,注释用于解释源代码
Python –数据类型数据类型定义变量的类型
前言本教程学习在Python中使用CSV文件
了解python中的变量,声明局部变量和全局变量
​Python关键字是python编程语言的保留字,这些关键字不能用于其他目的
Python httplib2 简介学习使用Python httplib2模块
Python OrderedDict,一个OrderedDict 维护插入顺序添加到字典中的项目
​​​​​​​​Python 语言中的String在Python中,String代指以下特点:代表Unicode字符的字节数组用单引号或双引号引起来无限长度Python 中 String 字符串...
Python string.startswith()方法用于检查特定文本模式(例如URL方案等)的字符串以什么开头