0

I am trying to insert a new index after splitting a string but it produces no value. Can anyone help?

#splitting of string
str = "my name is anant raj rathore"

var = (str.split(" "))

print(var)

# Fetching value from the split string
print(var[1])

# inserting in list--------here is the problem the result is none .
print(var.insert(3, 'sir'))

I know I am doing some mistake but don't know the exact issue

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
anant raj
  • 5
  • 4

2 Answers2

0

A couple of things to fix here. First of all don't name your variables things like list, tuple, str, int, float etc. Second of all split, by default will split at if you leave it blank.

And your main problem is that var.insert() won't return anything. It just modifies an iterable. So storing it in a variable won't do any good either. Just keep var.insert() plain and simple.

strEx = "my name is anant raj rathore"

var = strEx.split()
print(var)
# Fetching value from the split string
print(var[1])

# inserting in list--------here is the problem the result is none .
var.insert(3, 'sir')

Allow me to share an example. Say we had a function which added a char to the end of a list.

example = ['a','b']
def add_to_end(li,cha):
    li.append(cha)
add_to_end(example,'c')

Here, it does not have a return statement. It modified example by using append. If we print example like this.

example = ['a','b']
def add_to_end(li,cha):
    li.append(cha)
add_to_end(example,'c')
print(example)

we get the correct output, with no None.

['a', 'b', 'c']

But say we printed the function, even though it has not return.

example = ['a','b']
def add_to_end(li,cha):
    li.append(cha)
print(add_to_end(example,'c'))

we get None. Another option we have it to store it in a variable, example.

example = ['a','b']
def add_to_end(li,cha):
    li.append(cha)
example = add_to_end(example,'c')
print(example)

we get None once again.

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
0

insert() method inserts object obj into list at offset index. does not return any value but it inserts the given element at the given index.

print(var.insert(3, 'sir')) #None

So do print after calling insert.

var.insert(3, 'sir')
print(var) #['my', 'name', 'is', 'sir', 'anant', 'raj', 'rathore']
XMehdi01
  • 5,538
  • 2
  • 10
  • 34