How to use the str function in Python?

In Python, str is a built-in string class that can be used to represent and manipulate strings. Here are some commonly used str methods and operations:

  1. To create a string, you can use single quotes, double quotes, or triple quotes, for example:
s1 = 'Hello, World!'  # 使用单引号创建字符串
s2 = "Hello, World!"  # 使用双引号创建字符串
s3 = """Hello, 
World!"""  # 使用三引号创建多行字符串
  1. Accessing characters in a string: Individual characters in a string can be accessed using indexes, with the index starting at 0, for example:
s = "Hello, World!"
print(s[0])  # 输出:H
print(s[7])  # 输出:W
  1. To obtain the length of a string, you can use the len() function, for example:
s = "Hello, World!"
print(len(s))  # 输出:13
  1. Slicing: You can use slicing to get a substring of a string, for example:
s = "Hello, World!"
print(s[0:5])  # 输出:Hello
print(s[7:])  # 输出:World!
  1. String concatenation: You can use the + operator to combine two strings, for example:
s1 = "Hello"
s2 = "World"
s3 = s1 + " " + s2
print(s3)  # 输出:Hello World
  1. Formatting Strings: The format() method can be used to format strings, for example:
name = "Alice"
age = 25
s = "My name is {} and I am {} years old.".format(name, age)
print(s)  # 输出:My name is Alice and I am 25 years old.
  1. There are many methods commonly used for manipulating and handling strings in the str class, such as:
s = "Hello, World!"
print(s.upper())  # 输出:HELLO, WORLD!
print(s.lower())  # 输出:hello, world!
print(s.replace("Hello", "Hi"))  # 输出:Hi, World!
print(s.split(","))  # 输出:['Hello', ' World!']

This is just a part of string manipulation, the str class has many other methods and functions. You can refer to the official Python documentation for more detailed information.

bannerAds