英文:
Dividing the substring with equal parts on the both side while having three consecutive characters as the divider
问题
接受一个字符串作为输入。如果输入字符串的长度为奇数,则继续处理。如果输入字符串的长度为偶数,通过以下两个步骤将其变成奇数长度的字符串:
- 如果最后一个字符是句号(period),则将其删除。
- 如果最后一个字符不是句号,则在字符串末尾添加一个句号。
将这个奇数长度的字符串称为 "word"。从 "word" 中选择一个由三个连续字符组成的子字符串,使得这个子字符串的左右两侧有相等数量的字符。将这个子字符串打印为输出。可以假设所有输入字符串都是小写,并且至少包含四个字符。
你尝试的代码的第一部分已经解决了,但是对于第二部分,我似乎没有任何思路。
英文:
Accept a string as input. If the input string is of odd length, then continue with it. If the input string is of even length, make the string of odd length by following the two steps mentioned below:
- If the last character is a period, then remove it
- If the last character is not a period, then add a period to the end of the string
Call this string of odd length word. Select a substring made up of three consecutive characters from word such that there are an equal number of characters to the left and right of this substring. Print this substring as output. You can assume that all input strings will be in lower case and will have a length of at least four.
I just tried:
s1 = input()
s1 = s1.lower()
if (len(s1))%2==0:
if s1[-1]==".":
s1.replace(".","")
if s1[-1]!=".":
s1.join(".")
word = s1
print(word)
The first part has been solved but for second part I can't seem to have any ideas
答案1
得分: 1
为了在字符串的末尾添加句点(.
),使用 +=
符号。
要获取字符串中间的三个连续字符,有两种方法:
- 使用循环:如果
s1
的长度为奇数,则移除第一个字符,否则移除最后一个字符,重复此过程直到s1
的长度为3。
while len(s1) > 3:
if len(s1) % 2 == 0:
s1 = s1[:-1]
else:
s1 = s1[1:]
- 直接使用这个公式切片字符串:
s1[(len(s1) - 3) // 2 : (len(s1) + 3) // 2]
第一种方法:
s1 = input()
s1 = s1.lower()
if (len(s1)) % 2 == 0:
if s1[-1] == ".":
s1.replace(".", "")
else:
s1 += '.'
while len(s1) > 3:
if len(s1) % 2 == 0:
s1 = s1[:-1]
else:
s1 = s1[1:]
word = s1
print(word)
第二种方法:
s1 = input()
s1 = s1.lower()
if (len(s1)) % 2 == 0:
if s1[-1] == ".":
s1.replace(".", "")
else:
s1 += '.'
word = s1[(len(s1) - 3) // 2 : (len(s1) + 3) // 2]
print(word)
英文:
To add period(.
) to the end of the string, use +=
sign.
To get three consecutive characters at the middle of the string, you can do in 2 ways:
- Use looping: if
s1
is odd, then remove the first character, else remove the last character. Do that until length ofs1
is 3.
while len(s1) > 3:
if len(s1) % 2 == 0:
s1 = s1[:-1]
else:
s1 = s1[1:]
- Just slice the string with this formula:
s1[(len(s1) - 3) // 2 : (len(s1) + 3) // 2]
First way:
s1 = input()
s1 = s1.lower()
if (len(s1))%2==0:
if s1[-1]==".":
s1.replace(".","")
else:
s1 += '.'
while len(s1) > 3:
if len(s1) % 2 == 0:
s1 = s1[:-1]
else:
s1 = s1[1:]
word = s1
print(word)
Second way:
s1 = input()
s1 = s1.lower()
if (len(s1))%2==0:
if s1[-1]==".":
s1.replace(".","")
else:
s1 += '.'
word = s1[(len(s1) - 3) // 2 : (len(s1) + 3) // 2]
print(word)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论