简体   繁体   English

Python作业,中点和舍入字符串

[英]Python homework, midpoints and rounding strings

These are the steps given by my professor,: 这些是我的教授给出的步骤:

  1. Assume user will enter string with at least 1 character 假设用户将输入至少包含1个字符的字符串
  2. Store the input as user_input 将输入存储为user_input
  3. Calculate length of user input 计算用户输入的长度
  4. Store this as 'string_length' 将此存储为“ string_length”
  5. Print message stating whether length is even or odd 6.print "length is" and the length of the string 打印消息,说明长度是偶数还是奇数6.print“ length is”和字符串的长度
  6. Assume user will input either 'h1', 'div' or 'article' 假设用户将输入“ h1”,“ div”或“ article”
  7. Store this input as variable 'tag' 将此输入存储为变量“标签”

  8. Calculator half the length of the string_length, rounded down 计算器长度为string_length的一半,四舍五入

  9. Store this value as 'midpoint' 将此值存储为“中点”
  10. Calculate a new string that is the first half of 'user_input' using midpoint 使用中点计算新字符串,即“ user_input”的前半部分
  11. Store this as 'first_half' 将此存储为“ first_half”

  12. Calculate a new string that is the concatenation of 'tag' and 'first_half' in the following format first_half 计算一个新字符串,该字符串是“ tag”和“ first_half”的并置,格式如下:first_half

  13. Store this value in a variable called tagged_input. 将此值存储在一个名为tagd_input的变量中。

Attached is the code I've already run. 附带的是我已经运行的代码。 Everything works fine up until I start with the "tag" variable being defined. 一切正常,直到我开始定义“ tag”变量。 So basically around step 9 and onward I have issues. 所以基本上在第9步及以后,我遇到了问题。

user_input=input ("Please enter something")
string_length=len(user_input)
even_message= string_length % 2

if even_message>0:
print ("The length is", string_length, "characters long and is 
odd.")

else:
print ("Your length is", string_length, "characters long and is 
even.")

tag= input("Input one of the following: h1, div or article.")

midpoint = (string_length/2)
first_half= (midpoint)
tagged_input= print ((tag) + (midpoint) + "/" + (tag))

Output should be this. 输出应该是这样。 (uploaded a screenshot to imgur) (将屏幕截图上传到了imgur)

https://imgur.com/a/ogiTQiH https://imgur.com/a/ogiTQiH

this should work(replace the last 3 lines of your code with this): 这应该工作(用此代码替换代码的最后3行):

midpoint = (string_length//2)
first_half = user_input[:midpoint]
tagged_input = f"<{tag}>{first_half}</{tag}>"

(1) the first line uses the // operator, that divides and rounds down (1)第一行使用//运算符,对运算符进行除法和舍入

(2) the second line uses list/sequence slicing: Understanding slice notation (2)第二行使用列表/序列切片: 了解切片符号

(3) the third line uses a fairly new and very useful feature of python called f-strings: https://realpython.com/python-f-strings/ (3)第三行使用python的一个相当新且非常有用的功能,称为f-strings: https : //realpython.com/python-f-strings/

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

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