[Python] How to handle strings gracefully (1)

[Python] Practical simple case of processing strings

1. Capitalize the first letter

Use ***str.capitalize()*** method to convert the first character of the string to uppercase.

string = "hello world"
capitalized_string = string.capitalize()
print(capitalized_string)  
# 输出 "Hello world"

2. Split the string into a list according to the delimiter

Use ***str.split()*** method to split the string into a list according to the specified delimiter. If no delimiter is specified, spaces are used by default.

string = "apple,orange,banana"
fruits_list = string.split(",")
print(fruits_list)  
# 输出 ["apple", "orange", "banana"]

3. Concatenate the strings into a new string

Use the ***str.join()*** method to concatenate the elements of a list of strings (or other iterable objects) into a new string. The parameter of this method is an iterable object, each element is the string to be concatenated.

fruits_list = ["apple", "orange", "banana"]
joined_string = ",".join(fruits_list)
print(joined_string)  
# 输出 "apple,orange,banana"

4. Remove the spaces in the string

Use the ***str.strip()*** method to remove spaces at the beginning and end of a string. If you need to remove the spaces in the middle of the string, you can use the str.replace() method.

string = "  hello world  "
stripped_string = string.strip()
print(stripped_string)  
# 输出 "hello world"

strip() added:

The strip() function can be used to remove the specified characters at the beginning and end of the string (the default is a space or a newline) or a sequence of characters;
Note: this method can only delete the characters at the beginning or end, but not the characters in the middle .

# 只要头尾包含有指定字符序列中的字符就删除
id_list = [1, 2, 3, 4]
sql = f"select * from user where 1 = 1 and id in ({
      
      str(id_list).strip('[]')})"
print(sql) 
# 输出 "select * from user where 1 = 1 and id in (1, 2, 3, 4)"

5. String formatting

Method 1: Use ***str.format()*** method to replace the placeholder in a string with the specified value. A placeholder is represented by a pair of curly braces {}, where the parameter name, formatting method and other information can be specified.

name = "Alice"
age = 25
formatted_string = "My name is {} and I'm {} years old.".format(name, age)
print(formatted_string)  
# 输出 "My name is Alice and I'm 25 years old."

Method 2: f-string in Python, where variables can be enclosed in curly braces {} and preceded by the letter "f" to indicate that this is a formatted string.

name = "Alice"
age = 25
formatted_string = f"My name is {
      
      name} and I'm {
      
      age} years old."
print(formatted_string)  
# 输出 "My name is Alice and I'm 25 years old."

Guess you like

Origin blog.csdn.net/yqyn6/article/details/129810555