Python字符串

一. 字符串创建

  • Python中,字符串可以使用单引号、双引号或三重引号来创建。
  • 使用单引号或双引号创建的字符串是一行字符串。
  • 使用三重引号创建的字符串可以包含多行文本。
  • str1 = 'Hello, World!'  # 单引号
    str2 = "Hello, World!"  # 双引号
    str3 = '''Hello, World!'''  # 三重引号
    str4 = """Hello, World!"""  # 三重引号
    multiline_string = """This is a
    multiline
    string."""
    

    二. 字符串拼接

    1. 使用 + 运算符

    最简单的方法是使用 + 运算符将两个字符串拼接起来。

  • str1 = "Hello, "
    str2 = "World!"
    result = str1 + str2
    print(result)  # 输出: Hello, World!
    

    三. 字符串索引和切片

    1. 字符串索引

  • Python中,字符串中的每个字符都有一个索引,可以用来访问该字符。

  • 字符串的第一个字符的索引是 0,第二个字符的索引是 1,依此类推。

s = "Hello, World!"
print(s[0])  # 输出: H
print(s[7])  # 输出: W
print(s[-1])  # 输出: !(负索引表示从末尾开始计数)

 

2. 字符串切片

  • 切片使用 start:stop:step 的形式,其中 start 表示起始索引,stop 表示结束索引(不包括该索引对应的字符),step 表示步长(默认为1)。
s = "Hello, World!"
print(s[7:])    # 输出: World!(从索引7开始到结尾)
print(s[:5])    # 输出: Hello(从开头到索引5之前)
print(s[3:8])   # 输出: lo, W(从索引3到索引8之前)
print(s[::2])   # 输出: Hlo ol!(每隔一个字符取一个)
print(s[::-1])  # 输出: !dlroW ,olleH(反转字符串)

 

3. 字符串长度

  • len() 函数获取字符串的长度。

 

s = "Hello, World!"
print(len(s))     # 输出: 13

 

4. 字符串不可变性

  • 字符串是不可变的,不能直接修改字符串中的某个字符,但可以通过切片和拼接来达到类似的效果。
s = "Hello, World!"
# s[0] = 'h'  # 这会引发错误,字符串不可变
new_s = 'h' + s[1:]  # 使用切片和拼接来实现字符串的修改
print(new_s)  # 输出: hello, World!

 

四. 字符串转换 

1.s.upper()

  • 返回字符串的大写版本。
s = "hello"
print(s.upper())  # 输出: HELLO

 

2.s.lower()

  • 返回字符串的小写版本。

 

s = "HELLO"
print(s.lower())  # 输出: hello

 3.s.capitalize()

返回字符串的首字母大写版本,其余字母小写。

s = "hello"
print(s.capitalize())  # 输出: Hello

4.s.title()

  • 返回字符串中每个单词的首字母大写的版本。
s = "hello world"
print(s.title())  # 输出: Hello World

 

 五.查找字符串

1.find(substring, start, end) 方法:

find() 方法用于在字符串中查找子字符串 substring 第一次出现的位置,并返回其索引值。如果未找到子字符串,则返回 -1。

可选参数 start 和 end 可以指定查找子字符串的起始和结束位置。

s = "hello world"
print(s.find("world"))   # 输出: 6
print(s.find("python"))  # 输出: -1

2.index(substring, start, end) 方法:

index() 方法与 find() 方法类似,用于在字符串中查找子字符串 substring 第一次出现的位置,并返回其索引值。如果未找到子字符串,则会抛出异常。
可选参数 start 和 end 可以指定查找子字符串的起始和结束位置。

s = "hello world"
print(s.index("world"))   # 输出: 6
# print(s.index("python"))  # 会抛出异常 ValueError: substring not found

你可能感兴趣的:(python,java,服务器)