简体   繁体   English

如何将字符串的长度除以 2,然后根据结果在一行中打印切片版本

[英]How to divide string's length by 2 and then print sliced version based on result in one line

my_daily_thought = "I am the first half I am the second half"
print(len(my_daily_thought)//2)

How can i print "I am the second half" after finding my_daily_thought variable's divided length in one line?在一行中找到 my_daily_thought 变量的分割长度后,如何打印“我是后半部分”?

Output should be "I am the second half" instead of 20.输出应该是“我是下半场”而不是 20。

@dreadnaught thank you for your answer. @dreadnaught 谢谢你的回答。

You can treat strings in python as a list of characters and thus slice it as such:您可以将 python 中的字符串视为字符列表,从而将其切片:

my_daily_thought = "I am the first half I am the second half"
print(my_daily_thought[:len(my_daily_thought)//2])

print(my_daily_thought[len(my_daily_thought)//2:])

note that you can leave the 0 out in: my_daily_thought[0:10] to express that you slice from the start.请注意,您可以将 0 保留在: my_daily_thought[0:10]以表示您从一开始就切片。 Just like you can slice until the end as in the second slice就像你可以像第二片一样切到最后一样

In your code you call the print() function on the statement: len(my_daily_thought)//2 but this statement evaluates to a number (as len() evaluates to the length of the array and dividing it by 2 also returns a number) and so that is why you print the number 20在您的代码中,您在语句中调用 print() 函数: len(my_daily_thought)//2但该语句计算结果为一个数字(因为len()计算结果为数组的长度并将其除以 2 也返回一个数字)所以这就是为什么你打印数字 20

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

相关问题 如何在python中根据序列中的长度划分字符串? - How to divide the string depending on length in seqeunce in python? 当文本的长度超过 Python 中的窗口大小时,如何打印新行或自动打印新行? - How to print a new line or automatically print new line when the text's length is over the windows size in Python? 无论Python版本如何,如何在一行中打印iterable? - How to print iterable in one line regardless of the python version? 如何在二维数组的一行中获取 python 打印结果 - How to Get python print result in one line for 2d array 如何打印一行? - How to print in one line? 如何使用 python 中的字符串水平打印循环结果? - How to print a loop's result horizontally with a string in python? 我怎样才能让这个 function 根据我指定的数字在多行(每行一个单词)中打印字符串? - How can I make this function print the string in multiple lines (one word in each line) based on the number I specify? 如果一行以字符串开头,则打印该行和以下一行 - If a line starts with a string print THAT line and THE FOLLOWING one 如何一次延迟打印多行字符串一次? - How to print a multiline string one line at a time with a delay? 如何在 Python Flask 中的一行中打印字符串列表 - How to print list of string in one line in Python Flask
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM