Python3筆記(1)-字串去除空格的方法小結
阿新 • • 發佈:2018-11-05
可以考慮多次切割,然後判斷空字串,並重新生成新的list
def get_variable_attribute(self, path_map_file): attribute_list = [] file_map = open(file=path_map_file, mode="r", encoding="UTF-8") map_lines_list = file_map.readlines() file_map.close() for line in map_lines_list: if self.name in line: # other method for variable address # self.start_address = line[0:10] # self.end_address = line[11:21] new_line = line.split(" ", 10) for str in new_line: if str != "": attribute_list.append(str) self.start_address = attribute_list[0].upper() self.end_address = attribute_list[1].upper() self.size = attribute_list[2] break
1:strip()方法,去除字串開頭或者結尾的空格
>>> a = " a b c "
>>> a.strip()
'a b c'
2:lstrip()方法,去除字串開頭的空格
>>> a = " a b c "
>>> a.lstrip()
'a b c '
3:rstrip()方法,去除字串結尾的空格
>>> a = " a b c "
>>> a.rstrip()
' a b c'
4:replace()方法,可以去除全部空格
# replace主要用於字串的替換replace(old, new, count)
>>> a = " a b c "
>>> a.replace(" ", "")
'abc'
5: join()方法+split()方法,可以去除全部空格
# join為字元字串合成傳入一個字串列表,split用於字串分割可以按規則進行分割
>>> a = " a b c "
>>> b = a.split() # 字串按空格分割成列表
>>> b ['a', 'b', 'c']
>>> c = "".join(b) # 使用一個空字串合成列表內容生成新的字串
>>> c 'abc'
# 快捷用法
>>> a = " a b c "
>>> "".join(a.split())
'abc'