【问题标题】:Python - print split line starting at the n-th elementPython - 从第 n 个元素开始打印分割线
【发布时间】:2018-10-05 08:48:00
【问题描述】:

我有一个字符串作为文件中的 line.split 的结果。 如何将此字符串写入从第 5 个元素开始的另一个文件?

编辑: 我得到了这个并且它有效:

for line in data.readlines ()
if not line.startswith ("H"):
s = line.split ()
finaldata.write (" ".join (s [5:]))
finaldata.write ("\n")

唯一的问题是我的输入中有一些空的“单元格”,这会弄乱输出(将数据移动到原始输入有空白的左侧)

我该怎么做?

谢谢!

【问题讨论】:

  • 您知道如何split 字符串,对吧?你知道如何对列表进行切片,例如lst[1:] 以获取第一个元素之后的所有内容吗?从这两个中,您应该可以在这里找出答案。
  • 查找和替换 what?
  • 甚至不需要拆分,只需print(s[s.index('e'):]),尽管如果您的字母重复,您应该使用数字索引。
  • @chrisz 这只有在他的每个字符串都是"a b c d e f g h" 时才有效——在这种情况下,只使用print("e f g h") 会更简单。
  • 我有一个字符串 s=line.split () ,我不知道如何使用 slice 从第 4 个开始打印 s 元素。我还想找到元素“A1”和“R1”并将这些元素替换为“P1”和“2”

标签: python list split line


【解决方案1】:

回答原始问题:如果您通过计数知道元素,则应该对字符串进行切片。 string[5:] 将第 5 个字符打印到行尾。切片有一个非常基本的语法。假设你有一个字符串

a = "a b c d e f g h" 

你可以像这样从第 5 个字符开始切“a”

>>> a[5:] 
' d e f g h'

切片语法是 [start:end:step] 。所以 [5:] 说从 5 开始并包括其余部分。这里有很多例子Understanding Python's slice notation

第二个问题并不完全清楚您要实现的目标...以下是使用内联 cmets 进行常见标准字符串操作的一些示例

>>> a = "a b c d e f g h"
>>> a[5] # Access the 5th element of list using the string index
' '  
>>> a[5:] # Slice the string from the 5th element to the end
' d e f g h'  
>>> a[5::2] # Get every other character from the 5th element to the end
'     '
>>> a[6::2] # Get every other character from the 6th element to the end
'defgh'
# Use a list comprehension to remove all spaces from a string
>>> "".join([char for char in a if char != " "]) 
'abcdefgh'
# remove all spaces and print from the fifth character
>>> "".join([char for char in a if char != " "])[5:] 
'fgh'
>>> a.strip(" ") # Strip spaces from the beginning and end
'a b c d e f g h' 
>>> a[5:].strip(" ")  # slice and strip spaces from both sides
'd e f g h'
>>> a[5:].lstrip(" ")  # slice and use a left strip
'd e f g h'

编辑:添加来自其他用户的评论。如果您知道角色而不是位置,则可以从中切分。不过,如果你有重复的字符,你必须小心。

>>> a[a.index("e"):] # Slice from the index of character
'e f g h'
>>> b = "a e b c d e f g h e"
>>> b[b.index("e"):]
'e b c d e f g h e'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    相关资源
    最近更新 更多