There are many methods of string cutting and splicing in Python. The following will introduce the commonly used methods and attach code examples.
str1 = "Hello, World!" parts = str1.split(",") # 使用逗号进行切割 print(parts) # 输出:['Hello', ' World!']
parts = ['Hello', 'World!'] str1 = ", ".join(parts) # 使用逗号和空格进行拼接 print(str1) # 输出:Hello, World!
str1 = "Hello, World!" part1 = str1[:5] # 切割前五个字符 part2 = str1[7:] # 从第七个字符开始切割 print(part1) # 输出:Hello print(part2) # 输出:World!
str1 = "Hello" str2 = "World!" str3 = str1 + ", " + str2 # 使用加号进行拼接 print(str3) # 输出:Hello, World!
name = "John" age = 25 str1 = "My name is {} and I am {} years old.".format(name, age) print(str1) # 输出:My name is John and I am 25 years old.
name = "John" age = 25 str1 = f"My name is {name} and I am {age} years old." print(str1) # 输出:My name is John and I am 25 years old.
The above are the commonly used string cutting and splicing methods in Python. You can choose the appropriate method according to actual needs.
The above is the detailed content of What are the string cutting and splicing methods in Python?. For more information, please follow other related articles on the PHP Chinese website!