# Python中字符串如何创建使用 字符串是Python中最常用的数据类型之一,用于表示文本信息。本文将详细介绍字符串的创建方式、基本操作以及常用方法。 ## 一、字符串的创建 在Python中,字符串可以通过多种方式创建: ### 1. 使用引号创建 ```python # 单引号 str1 = 'Hello World' # 双引号 str2 = "Python Programming" # 三引号(多行字符串) str3 = '''This is a multi-line string''' str4 = str(123) # 将数字转换为字符串"123" name = "Alice" str5 = f"My name is {name}" s1 = "Hello" s2 = "World" result = s1 + " " + s2 # "Hello World" s = "Python" repeated = s * 3 # "PythonPythonPython" text = "Python" first_char = text[0] # 'P' last_char = text[-1] # 'n' text = "Programming" sub1 = text[0:7] # "Program" sub2 = text[3:] # "gramming" s = "Python" print(s.upper()) # "PYTHON" print(s.lower()) # "python" text = "Hello World" print(text.find("World")) # 6 print(text.replace("World", "Python")) # "Hello Python" csv = "apple,banana,orange" fruits = csv.split(",") # ['apple', 'banana', 'orange'] words = ["Python", "is", "great"] sentence = " ".join(words) # "Python is great" s = " Python " print(s.strip()) # "Python" print(s.lstrip()) # "Python " print(s.rstrip()) # " Python" # 旧式格式化 print("My name is %s, age %d" % ("Alice", 25)) # format方法 print("My name is {}, age {}".format("Alice", 25)) # f-string(推荐) name = "Alice" age = 25 print(f"My name is {name}, age {age}") Python中的字符串是不可变对象:
s = "Python" # s[0] = "J" # 会报错 # 正确做法是创建新字符串 new_s = "J" + s[1:] # "Jython" 常用转义字符: - \n 换行 - \t 制表符 - \\ 反斜杠 - \" 双引号 - \' 单引号
path = "C:\\Users\\Name\\file.txt" print("Line1\nLine2") 在字符串前加r可忽略转义:
path = r"C:\Users\Name\file.txt" 字符串操作是Python编程的基础,掌握这些基本概念和方法将大大提高你的编程效率。随着学习的深入,你还会接触到更高级的字符串处理技术,如正则表达式等。 “`
注:本文约800字,涵盖了字符串创建、基本操作、常用方法等核心内容,采用Markdown格式编写,代码部分使用代码块突出显示。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。