返回

剖析 ${ } 引用变量的高级用法,开启编程新视野

后端

${ } 引用变量的高级用法

1. 字符串删除

1.1 删除开头或结尾的整段字符串

格式:

${string}.lstrip("string")
${string}.rstrip("string")

示例:

>>> name = "  John Smith  "
>>> name.lstrip()
'John Smith  '
>>> name.rstrip()
'  John Smith'

演示1:

# 删除字符串开头的空格
name = "   Hello World"
cleaned_name = name.lstrip()
print(cleaned_name)  # 输出: "Hello World"

演示2:

# 删除字符串结尾的换行符
message = "Thank you!\n"
cleaned_message = message.rstrip()
print(cleaned_message)  # 输出: "Thank you!"

1.2 删除中间的某个字符或单词

格式:

${string}.replace("old_string", "new_string", count)

示例:

>>> name = "John Smith"
>>> name.replace("Smith", "Doe")
'John Doe'

演示:

# 删除字符串中间的逗号
text = "Hello, World, how are you?"
cleaned_text = text.replace(",", "")
print(cleaned_text)  # 输出: "Hello World how are you?"

2. 字符串替换

格式:

${string}.replace("old_string", "new_string", count)

示例:

>>> name = "John Smith"
>>> name.replace("Smith", "Doe")
'John Doe'

演示:

# 将字符串中的所有 "John" 替换为 "Mary"
text = "John went to the store. John bought some groceries. John paid for them and left."
replaced_text = text.replace("John", "Mary")
print(replaced_text)  # 输出: "Mary went to the store. Mary bought some groceries. Mary paid for them and left."

3. 字符串切片

格式:

${string}[start:stop]
${string}[start:]
${string}[:stop]

示例:

>>> name = "John Smith"
>>> name[0:5]
'John '
>>> name[6:]
'Smith'

演示:

# 获取字符串的前三个字符
text = "Hello World"
sliced_text = text[:3]
print(sliced_text)  # 输出: "Hel"

# 获取字符串从第五个字符开始的所有字符
text = "Hello World"
sliced_text = text[4:]
print(sliced_text)  # 输出: "lo World"

# 获取字符串的最后三个字符
text = "Hello World"
sliced_text = text[-3:]
print(sliced_text)  # 输出: "rld"

结语

通过本文对 ${ } 引用变量的高级用法的剖析,您已经掌握了在编程中操作字符串的技巧。无论是删除开头或结尾的整段字符串,删除中间的某个字符或单词,还是进行字符串替换或切片,您都可以轻松应对。这些技巧将成为您编程生涯中的利器,帮助您编写出更简洁、更高效的代码。