要判断一个字符串'xxx'的前后是否有空格,可以使用以下方法:

  1. 使用'strip()'函数去除字符串前后的空格,并将去除空格后的字符串与原字符串进行比较。如果相等,则说明原字符串前后没有空格。
string = 'xxx'
trimmed_string = string.strip()
if string == trimmed_string:
    print('前后没有空格')
else:
    print('前后有空格')
  1. 使用正则表达式'^\sxxx\s$'进行匹配,判断字符串的前后是否有空格。
import re

string = 'xxx'
pattern = r'^\s*xxx\s*$'
match = re.match(pattern, string)
if match:
    print('前后没有空格')
else:
    print('前后有空格')

以上两种方法都可以判断字符串'xxx'的前后是否有空格,可以根据实际情况选择使用。

Python判断字符串前后是否有空格的两种方法

原文地址: https://www.cveoy.top/t/topic/ljFK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录