溫馨提示×

python中str的用法

小億
117
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女