【问题标题】:Is it possible to split a string in half at a specific point?是否可以在特定点将字符串分成两半?
【发布时间】:2020-10-03 07:28:23
【问题描述】:

我需要将我已经完成的字符串分成两半:

firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]

我需要它在换行符处拆分,而且我对编码太陌生,不知道如何处理这个问题。任何提示都会有所帮助。

【问题讨论】:

  • 你想要哪个,将它分成一半,还是在换行符处拆分?
  • 在最近的换行符处减半。
  • 举个输入输出的例子。
  • @BirdLeaf 请提供输入示例并明确显示您希望如何拆分它。一个具体的例子将帮助人们准确地回答你的问题。

标签: python python-3.x string split string-length


【解决方案1】:

假设字符串只有一个换行符。

那就是:

firstpart, secondpart = string.split('\n')

【讨论】:

  • 我的主要问题是有多个换行符,我不知道如何区分在哪一个。
【解决方案2】:

您可以使用splitlines 方法,该方法非常适合您的情况,

str1="hope\n this helps\n you"
print(str1.splitlines())

输出:

['hope', ' this helps', ' you']

它返回一个拆分字符串的列表。

希望对您有所帮助!

【讨论】:

  • 不客气,很高兴为您提供帮助!
  • 附在问题上的评论说,要求将“在最近的换行符处分成两半”。这将拆分为一个列表,每行一个元素(在本例中为三个)。
【解决方案3】:

试试这样的:

mystring = """Mae hen wlad fy nhadau yn annwyl i mi,
Gwlad beirdd a chantorion, enwogion o fri;
Ei gwrol ryfelwyr, gwladgarwyr tra mad,
Dros ryddid collasant eu gwaed.

Gwlad!, GWLAD!, pleidiol wyf i'm gwlad.
Tra mor yn fur i'r bur hoff bau,
O bydded i'r hen iaith barhau.

Hen Gymru fynyddig, paradwys y bardd,
Pob dyffryn, pob clogwyn, i'm golwg sydd hardd;
Trwy deimlad gwladgarol, mor swynol yw si
Ei nentydd, afonydd, i fi.
"""

# get the half-way index
halfway = len(mystring) // 2

# get the indices of the nearest \n characters before and after the halfway
try:
    next_one = mystring.index("\n", halfway)
except ValueError:
    next_one = None

try:
    previous_one = mystring.rindex("\n", 0, halfway)
except ValueError:
    previous_one = None

# if no \n found at all, raise an error
if next_one == None and previous_one == None:
    raise ValueError

# or if a \n is only found on one side of halfway, use that one
elif next_one == None:
    pos = previous_one

elif previous_one == None:
    pos = next_one

# or if it is found on both sides of half-way, use whichever is nearer
elif next_one - halfway < halfway - previous_one:
    pos = next_one

else:
    pos = previous_one

# now actually split the string
part1 = mystring[:pos]
part2 = mystring[pos + 1:]

print("FIRST HALF:", part1)
print("==========")
print("SECOND HALF:", part2)

给予:

FIRST HALF: Mae hen wlad fy nhadau yn annwyl i mi,
Gwlad beirdd a chantorion, enwogion o fri;
Ei gwrol ryfelwyr, gwladgarwyr tra mad,
Dros ryddid collasant eu gwaed.

Gwlad!, GWLAD!, pleidiol wyf i'm gwlad.
==========
SECOND HALF: Tra mor yn fur i'r bur hoff bau,
O bydded i'r hen iaith barhau.

Hen Gymru fynyddig, paradwys y bardd,
Pob dyffryn, pob clogwyn, i'm golwg sydd hardd;
Trwy deimlad gwladgarol, mor swynol yw si
Ei nentydd, afonydd, i fi.

【讨论】:

  • previous_one 分配给 None 时拼写错误。
猜你喜欢
  • 2019-07-24
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
相关资源
最近更新 更多