如何不使用strip等相关函数移除Python字符串的尾部空白字符
不使用strip类函数移除字符串首尾空白的实现方法
通用自定义实现思路
核心逻辑是手动定位首尾第一个非空白字符的位置,再切片取有效内容,实现代码如下:
def custom_strip(s): # 空白字符可根据需求调整,这里包含空格、换行、制表符 whitespace = {' ', '\n', '\t'} n = len(s) start = 0 # 找左边界第一个非空白字符 while start < n and s[start] in whitespace: start += 1 if start == n: # 字符串全为空白字符 return '' end = n - 1 # 找右边界最后一个非空白字符 while end >= start and s[end] in whitespace: end -= 1 return s[start:end+1]
你在打印输出时把需要处理的字符串传入该函数即可,比如print(custom_strip(a))、print(custom_strip(b))。
针对你当前代码的优化方案
你代码里的多余空白是拼接字符串时主动生成的,完全可以从源头避免生成多余空格,不需要事后删除,修改后的代码如下:
r, c, p, a, std, b = 0, 0, 0, '', input('Standard game? (y/n): '), '' if std == 'y': r, c = 6, 7 else: r, c = int(input('r? (2 - 20): ')), int(input('c? (2 - 20): ')) if r < 11 and c < 11: for i in range (r-1, -1, -1): # 用join拼接分隔符,不会生成前后多余空格 row_content = [str(i)] + ['·']*c print(' '.join(row_content)) # 拼接底部数字行,空元素用于对齐上方行号位置 col_content = [''] + [str(j) for j in range(c)] print(' '.join(col_content))
内容的提问来源于stack exchange,提问作者Hannah K
相关产品推荐
相关产品推荐

