Replacing part of a string in a list in python
<p>For example i have list of a name written diffently  </p>

<pre><code>list1 = ["jai.kumar","jaikumar","j_kumar","jk","kumar-jai","ja.ku"]
for str in l1:
 if str == âjaiâ
  str.replace (âjaiâ,âfirstnameâ)
   if str == âjaâ
    str.replace (âjaâ,âfirst 2 character of firstnameâ)
     if str == âjâ
      str.replace (âjâ,âfirst character of firstnameâ)
 if str == âkumarâ
  str.replace (âkumarâ,âlastnameâ)
   if str == âkuâ
    str.replace (âkuâ,âfirst 2 character of lasttnameâ)
     if str == âkâ
      str.replace (âkâ,âfirst character of lastnameâ)
print(list1)
</code></pre>

<p>How do i correct the above code or is there an easier way to do it?</p>

<p>My expected output is</p>

<pre><code> list1 = ["firstname.lastname","firstnamelastname","first character of firstname_lastname",.....]
</code></pre>

<p>first of all, you're defining a list "list1" then operating on a list "l1" which is not defined, I'll assume this is a typo. Also you're indentation is fucked up and you're missing tons of colons after your ifs, I'll correct all that, if I shouldn't have and missed the purpose, please tell me.</p>

<p>second, you're using == for comparing strings which will only be true for exact matches. What you're looking for is the "in" operator.</p>

<p>thirdly, you're using string.replace("str1","str2") incorrectly, string.replace() returns a shallow copy of string where "str1" instances have been replaced by "str2", so what you'd want to do would be more like str = str.replace("1","2").</p>

<p>Fourth, </p>

<pre><code>for str in list1:
</code></pre>

<p>creates an str variable that is an alias of the list1 element, and reassigning str breaks the alias, meaning str = something will not modify list1.</p>

<p>and lastly, you won't encounter "ja" if you already encountered "jai" I assume, for that reason using elifs is more efficient, rather than testing for "ja" and "j" after already having found "jai"</p>

<p>All in all, your code would need to be something like this:</p>

<pre><code>list1 = ["jai.kumar","jaikumar","j_kumar","jk","kumar-jai","ja.ku"]
for i in range(len(list1)):
 if âjaiâ in list1[i]:
  list1[i] = list1[i].replace (âjaiâ,âfirstnameâ)
 elif âjaâ in list1[i]:
  list1[i] = list1[i].replace (âjaâ,âfirst 2 character of firstnameâ)
 elif âjâ in list1[i]:
  list1[i] = list1[i].replace (âjâ,âfirst character of firstnameâ)
 if âkumarâ in list1[i]:
  list1[i] = list1[i].replace (âkumarâ,âlastnameâ)
 elif âkuâ in list1[i]:
  str = str.replace (âkuâ,âfirst 2 character of lasttnameâ)
 elif "kâ in list1[i]:
  list1[i] = list1[i].replace (âkâ,âfirst character of lastnameâ)
print(list1)
</code></pre>

<p>Hope this answer your questions, let me know if anything is not clear.</p>

python