如何在Python中从字符串中读取特定行?

huangapple go评论53阅读模式
英文:

How do I read a specific line from a string in Python?

问题

如何在Python中从字符串中读取特定行?例如,假设我想要从以下字符串中获取第2行:

string = """The quick brown fox 
jumps over the
lazy dog."""
line = getLineFromString(string, 2)
print(line)  # jumps over the

关于从文件中读取特定行有几个问题,但如何从字符串中读取特定行呢?

英文:

How can I read a specific line from a string in Python? For example, let's say I want line 2 of the following string:

string = """The quick brown fox 
jumps over the
lazy dog."""
line = getLineFromString(string, 2)
print(line)  # jumps over the

There are several questions about reading specific lines from a file, but how would I read specific lines from a string?

答案1

得分: 2

在Python中,没有原始数据类型,因此您的字符串是一个对象。它具有方法,包括splitlines()

my_string = """The quick brown fox 
jumps over the
lazy dog."""

line = my_string.splitlines()[1]   # 从0开始的索引,所以1是第二行

print(line)  # 'jumps over the' 
英文:

There are no primitives in python, so your string is an object. Which has methods, including splitlines().

my_string = """The quick brown fox 
jumps over the
lazy dog."""

line = my_string.splitlines()[1]   # 0 based index, so 1 is the second line

print(line)  # 'jumps over the' 

答案2

得分: -1

你可以在换行符上拆分字符串,然后取结果数组的第N个元素。

string.split('\n')
# => ['The quick brown fox ', 'jumps over the', 'lazy dog.']

请记住,Python 数组是从0开始索引的,所以第2个元素在索引1处。

string.split('\n')[1]
# => 'jumps over the'
英文:

You can split the string on the newlines, then take the Nth element of the resulting array.

string.split('\n')
# => ['The quick brown fox ', 'jumps over the', 'lazy dog.']

Remember that Python arrays are 0-indexed, so the 2nd element is at index 1.

string.split('\n')[1]
# => 'jumps over the'

huangapple
  • 本文由 发表于 2023年3月4日 06:40:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定