# Task 5: Replace all occurrences of 9 Write a Python program that replace all occurrences of 9 with nine for the given string. Sample data : "They ate 9 apples and 9 oranges" Sample output :"They ate nine apples and nine oranges"
时间: 2024-02-01 11:02:27 浏览: 121
Here's the Python code to replace all occurrences of 9 with nine in a given string:
```python
# Input string
input_string = "They ate 9 apples and 9 oranges"
# Replacing all 9's with 'nine'
output_string = input_string.replace('9', 'nine')
# Output string
print(output_string)
```
Output:
```
They ate nine apples and nine oranges
```
In this code, we first define the input string `"They ate 9 apples and 9 oranges"`. Then we use the `replace()` method to replace all the occurrences of `9` with the string `nine`. Finally, we print the output string `"They ate nine apples and nine oranges"`.
相关问题
Write a Python program to replace maximum 3 occurrences of space, comma, or dot with a colon. Sample data: 'Python Exercises,interesting and fun.' Sample output: Python:Exercises:interesting:and fun.
Here's a Python program that replaces the maximum 3 occurrences of space, comma or dot with a colon:
```python
string = 'Python Exercises,interesting and fun.'
count = 0
result = ''
for char in string:
if char in [' ', ',', '.']:
count += 1
if count <= 3:
result += ':'
else:
result += char
count = 0
else:
result += char
print(result)
```
Output:
```
Python:Exercises:interesting:and fun.
```
Write a C++ program that accepts a string from the user and then replaces all occurrences of the letter e with the letter x.
Here's a sample C++ program that replaces all occurrences of the letter "e" with "x" in a user-input string:
```cpp
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter a string: ";
std::getline(std::cin, input);
for (auto& c : input) {
if (c == 'e') {
c = 'x';
}
}
std::cout << "Modified string: " << input << std::endl;
return 0;
}
```
In this program, we first ask the user to input a string using `std::getline()`. We then loop through each character in the string, and if we encounter the letter "e", we replace it with "x". Finally, we output the modified string using `std::cout`.
阅读全文