Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4fbcd5c

Browse files
Add files via upload
1 parent d077c2f commit 4fbcd5c

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

‎Mutations.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# We have seen that lists are mutable (they can be changed), and tuples are immutable (they cannot be changed).
2+
3+
# Let's try to understand this with an example.
4+
5+
# You are given an immutable string, and you want to make changes to it.
6+
7+
# Example
8+
9+
# >>> string = "abracadabra"
10+
# You can access an index by:
11+
12+
# >>> print string[5]
13+
# a
14+
# What if you would like to assign a value?
15+
16+
# >>> string[5] = 'k'
17+
# Traceback (most recent call last):
18+
# File "<stdin>", line 1, in <module>
19+
# TypeError: 'str' object does not support item assignment
20+
# How would you approach this?
21+
22+
# One solution is to convert the string to a list and then change the value.
23+
# Example
24+
25+
# >>> string = "abracadabra"
26+
# >>> l = list(string)
27+
# >>> l[5] = 'k'
28+
# >>> string = ''.join(l)
29+
# >>> print string
30+
# abrackdabra
31+
# Another approach is to slice the string and join it back.
32+
# Example
33+
34+
# >>> string = string[:5] + "k" + string[6:]
35+
# >>> print string
36+
# abrackdabra
37+
# Task
38+
# Read a given string, change the character at a given index and then print the modified string.
39+
40+
# Input Format
41+
# The first line contains a string, .
42+
# The next line contains an integer , denoting the index location and a character separated by a space.
43+
44+
# Output Format
45+
# Using any of the methods explained above, replace the character at index with character .
46+
47+
# Sample Input
48+
49+
# abracadabra
50+
# 5 k
51+
# Sample Output
52+
53+
# abrackdabra
54+
55+
56+
57+
58+
def mutate_string(string, position, character):
59+
l = list(string)
60+
l[position] = character
61+
string = "".join(l)
62+
return (string)
63+
64+
if __name__ == '__main__':
65+
s = input()
66+
i, c = input().split()
67+
s_new = mutate_string(s, int(i), c)
68+
print(s_new)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /