给定一个单词,如果该单词以er、ly或者ing后缀结尾, 则删除该后缀 python
时间: 2023-06-09 12:04:51 浏览: 81
可以使用字符串的.endswith() 方法来判断单词是否以指定后缀结尾,然后使用切片操作删除后缀。
具体代码如下:
```python
word = input("请输入一个单词:")
if word.endswith("er") or word.endswith("ly") or word.endswith("ing"):
word = word[:-2] # 删去后缀的两个字符
print("处理后的单词为:", word)
```
注意,在删除后缀时需要使用切片操作,将原字符串的末尾两个字符删除。如果直接使用字符串的.replace() 方法来替换后缀,可能会出现一些意外情况,比如单词本身就包含了er、ly或ing,导致替换出错。
相关问题
用Java写出完整代码完成以下条件:给定一个单词,如果该单词以er、ly或者ing后缀结尾, 则删除该后缀(题目保证删除后缀后的单词长度不为0), 否则不进行任何操作。
下面是完整的Java代码实现:
```java
public class WordSuffixRemover {
public static void main(String[] args) {
String word = "worker";
String newWord = removeSuffix(word);
System.out.println(newWord); // 输出work
word = "quickly";
newWord = removeSuffix(word);
System.out.println(newWord); // 输出quick
word = "eating";
newWord = removeSuffix(word);
System.out.println(newWord); // 输出eat
}
public static String removeSuffix(String word) {
if(word.endsWith("er")) {
return word.substring(0, word.length() - 2);
} else if(word.endsWith("ly")) {
return word.substring(0, word.length() - 2);
} else if(word.endsWith("ing")) {
return word.substring(0, word.length() - 3);
} else {
return word;
}
}
}
```
这个代码首先定义了一个`removeSuffix()`函数,用于删除单词的er、ly或ing后缀。然后在`main()`函数中调用这个函数进行测试。测试结果符合预期。
给定一个单词,如果该单词以er、ly或者ing后缀结尾, 则删除该后缀(题目保证删除后缀后的单词长度不为0), 否则不进行任何操作。 输入 输入一行,包含一个单词(单词中间没有空格,每个单词最大长度为32)。 用java
实现如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word = sc.nextLine();
if (word.endsWith("er") || word.endsWith("ly") || word.endsWith("ing")) {
word = word.substring(0, word.length() - 2);
}
System.out.println(word);
}
}