英文:
How to access number of iterations while looping over a string — Python
问题
def without_end(str):
first = str[0]
last = str[-1]
for i in str:
if i == first or i == last:
new_string = str.replace(i, "")
return new_string
英文:
I am trying to remove the first and last characters in a given string in python.
I want the if statement to replace the letter with an empty string, as the last line is attempting. But i is a str and not an int, so I cant use it to find the index in the replace function. I need some way to access the number of iterations to the string, and not the string letter itself, is there a simple thing I'm missing here?
def without_end(str):
first = str[0]
last = str[-1]
for i in str:
if i == first or i == last:
new_string = str.replace(str[i], "")
return new_string
答案1
得分: 1
在Python中,你可以执行以下操作。
x = "foof"
x = x[1:-1]
这将导致字符串 oo
。
英文:
In Python you can do the following.
x = "foof"
x = x[1:-1]
This will result in the string oo
.
答案2
得分: 1
在这个实现中,input_str[1:-1] 切片字符串以排除第一个和最后一个字符,有效地从原始字符串中移除它们。
避免使用 str 作为变量名,因为它是Python内置的类型,并且将其用作变量名可能会导致混淆和意外行为。我将参数重命名为 input_str 以避免任何冲突。
代码:
def without_end(input_str):
return input_str[1:-1]
# 测试函数
result = without_end("Hello")
print(result) # 输出: "ell"
根据反馈,下面的代码是正确的。我保留上面的代码以供不同角度的参考。
代码:
def without_end(input_str):
first = input_str[0]
last = input_str[-1]
new_string = "".join([char for char in input_str if char != first and char != last])
return new_string
# 测试
print(without_end("hello")) # 输出: "ell"
print(without_end("python")) # 输出: "ytho"
print(without_end("code")) # 输出: "od"
print(without_end("hellocode")) # 输出: "llocod"
英文:
In this implementation, input_str[1:-1] slices the string to exclude the first and last characters, effectively removing them from the original string.
Avoid using the name str as a variable, as it is a built-in Python type, and using it as a variable name may cause confusion and unexpected behavior. I renamed the parameter to input_str to avoid any conflicts.
Code:
def without_end(input_str):
return input_str[1:-1]
# Test the function
result = without_end("Hello")
print(result) # Output: "ell"
According to feedback, the below code is the correct one.
I leave the above code to stay there for a different perspective.
Code:
def without_end(input_str):
first = input_str[0]
last = input_str[-1]
new_string = "".join([char for char in input_str if char != first and char != last])
return new_string
# Tests
print(without_end("hello")) # Output: "ell"
print(without_end("python")) # Output: "ytho"
print(without_end("code")) # Output: "od"
print(without_end("hellocode")) # Output: "llocod"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论