Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Python by (45.3k points)

In Python, strings are immutable.

What is the standard idiom to walk through a string character-by-character and modify it?

The only methods I can think of are some genuinely stanky hacks related to joining against a result string.

--

In C:

for(int i = 0; i < strlen(s); i++)

{

   s[i] = F(s[i]);

}

This is super expressive and says exactly what I am doing. That is what I am looking for.

1 Answer

0 votes
by (16.8k points)
edited by

The Python analog of your C:

for(int i = 0; i < strlen(s); i++)

{

   s[i] = F(s[i]);

}

would be:

s = "".join(F(c) for c in s)

which is also very expressive. It says exactly what is happening but in a functional style rather than a procedural style.

To know more about this you can have a look at the following video:-

Related questions

0 votes
4 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jan 2, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer

Browse Categories

...