繁体   English   中英

是否可以在特定点将字符串分成两半?

[英]Is it possible to split a string in half at a specific point?

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

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

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

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

那将是:

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

您可以使用splitlines方法,该方法将在您的情况下完美运行,

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

output:

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

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

希望这对你有帮助!

尝试这样的事情:

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM