[英]How do I define a function to split a string into separate lines?
說,字符串看起來像:
我喜歡派。 你喜歡蘋果。 我們喜歡橘子。
我將如何定義一個名為format_poem()
的 function,它本質上會接受任何輸入與上面類似的段落,並將每個句子放在單獨的行中?
我確定它位於每句話之后的句號,但作為菜鳥,我無法理解它。 這是否也使用.split()
方法?
謝謝你的幫助。
使用.replace()
將句點替換為新行的字符(幾乎普遍是\n
)
def format_poem(paragraph):
return paragraph.replace('. ','\n')
你是對的: split
會做你需要的。
str = "I like pie. You like apples. We like oranges."
def format_poem(inStr):
t = inStr.split(". ")
return t
for el in format_poem(str):
print(el)
Output:
I like pie
You like apples
We like oranges.
或者,您可以打印 function 內的行,只需移動 function 內的 for 循環:
I like pie. You like apples. We like oranges.
def format_poem(inStr):
t = inStr.split(". ")
for el in t:
print(el)
為了保留句子末尾的句點,就像在原始字符串中一樣,您需要使用replace()
方法,搜索". "
並替換為".\n"
。 請注意此方法如何不修改原始字符串:
#Perform replacement
str2 = str1.replace(". ", '.\n')
#Print the original string
print(str1)
#Print new string, result of the replacement
print(str2)
新的 output 是:
#The original string
I like pie. You like apples. We like oranges.
#The newly assigned string
I like pie.
You like apples.
We like oranges.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.