[英]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.