w3resource

Python: Get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself

Python String: Exercise-4 with Solution

Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.

Python String Exercises: Get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself

Sample Solution:

Python Code:

# Define a function named change_char that takes one argument, 'str1'.
def change_char(str1):
    # Get the first character of the input string 'str1' and store it in the variable 'char'.
    char = str1[0]

    # Replace all occurrences of the character 'char' with '$' in the 'str1' string.
    str1 = str1.replace(char, '$')

    # Reconstruct the 'str1' string by placing the original 'char' as the first character
    # followed by the modified string starting from the second character.
    str1 = char + str1[1:]

    # Return the modified 'str1' string.
    return str1

# Call the change_char function with the argument 'restart' and print the result.
print(change_char('restart'))  # Output: 'resta$t' 

Sample Output:

resta$t

Flowchart:

Flowchart: Program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself

Python Code Editor:

Previous: Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string.
Next: Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/string/python-data-type-string-exercise-4.php