温馨提示×

python中str的用法

小亿
91
2024-01-05 16:07:37
栏目: 编程语言

在Python中,str是字符串类型的数据。以下是一些str的常见用法:

  1. 创建字符串:

    my_str = "Hello, World!"  # 使用双引号创建字符串
    my_str = 'Hello, World!'  # 使用单引号创建字符串
    my_str = """Hello, World!"""  # 使用三引号创建字符串,可以包含多行文本
    
  2. 字符串拼接:

    str1 = "Hello"
    str2 = "World"
    result = str1 + str2  # 字符串拼接
    
  3. 字符串索引和切片:

    my_str = "Hello, World!"
    print(my_str[0])  # 输出第一个字符 'H'
    print(my_str[7:12])  # 输出切片 'World'
    
  4. 字符串长度:

    my_str = "Hello, World!"
    length = len(my_str)  # 获取字符串长度
    
  5. 字符串常用方法:

    my_str = "Hello, World!"
    print(my_str.upper())  # 将字符串转换为大写 'HELLO, WORLD!'
    print(my_str.lower())  # 将字符串转换为小写 'hello, world!'
    print(my_str.replace("Hello", "Hi"))  # 将字符串中的指定子串替换 'Hi, World!'
    print(my_str.split(","))  # 将字符串按指定分隔符分割成列表 ['Hello', ' World!']
    
  6. 格式化字符串:

    name = "Alice"
    age = 25
    print("My name is {} and I am {} years old.".format(name, age))  # 使用占位符格式化字符串
    print(f"My name is {name} and I am {age} years old.")  # 使用f-string格式化字符串(Python 3.6及以上版本)
    

这些只是str的一些常见用法,str还有更多的方法和功能可供使用。

0