Python列表格式和更新

时间:2019-02-15 20:20:15

标签: python-3.x

我有一个清单,例如。 a = [“ dgbbgfbjhffbjjddvj / n // n // n'”] 如何删除尾随的换行符,即全部/ n末尾带有多余的单个反斜杠?

预期结果= [“ dfgjhgjjhgfjjfgg”](我随机输入)

2 个答案:

答案 0 :(得分:0)

您可以使用字符串rstrip()方法。

用法:

str.rstrip([c])

其中c是必须修剪的字符,如果未提供arg,则默认为空格。

示例:

a = ['Return a copy of the string\n', 'with trailing characters removed\n\n']                                 
[i.rstrip('\n') for i in a]

结果:

['Return a copy of the string', 'with trailing characters removed']

有关strip()的更多信息:

https://www.tutorialspoint.com/python3/string_rstrip.htm

答案 1 :(得分:0)

您在问题中输入的换行符不正确。以下是从列表中删除换行符的4种方法

mylist = ['dgbbgfbjhffbjjddvj\n\n\n', 'abcdgedft\n\n']

# Standard list for loop with rstrip
for item in mylist:
  print (item.rstrip("\n"))
  # output 
  dgbbgfbjhffbjjddvj
  abcdgedft


# Remove new lines with List Comprehension and strip
no_new_lines_option_01 = [i.strip() for i in mylist]
print (no_new_lines_option_01)
# output 
['dgbbgfbjhffbjjddvj', 'abcdgedft']


# Remove new lines with List Comprehension and rstrip
no_new_lines_option_02 = [(i.rstrip('\n')) for i in mylist]
print (no_new_lines_option_02)
# output 
['dgbbgfbjhffbjjddvj', 'abcdgedft']


# list call over map
no_new_lines_option_03 = list(map(str.strip, mylist))
print (no_new_lines_option_03)
# output 
['dgbbgfbjhffbjjddvj', 'abcdgedft']