How do I replace a string variable - python

I have a code as follows
with open(f1) as f:
userid=f.read().replace('0', str(instance.id))
The above works well. Now, the variable userid as a string has character In will like to replace. I tried this code and is given errors shown below. Please note: the variable the_user.phonelist is a python LIST. I will like to replace the character [] with the list.
ans = userid.replace('[]', the_user.phonelist)
Error: Can't convert 'list' object to str implicitly

As the error suggests, you have to convert the list to a string
One way to do this is with a join:
phonelist_str = ''.join(the_user.phonelist)
This only will work though if all the items in the list are strings. If not, you'll have to pair it with a list comprehension in order to cast all of the list's items to strings:
phonelist_str = ''.join([str(x) for x in the_user.phonelist])
Once you have a string, you can do your replace:
ans = userid.replace('[]', phonelist_str)

Related

Why do sequence for loops don't seem to work well in Python?

I'm trying to convert every string in a list to it's lowercase format using this function:
def lower_list(strings):
for string in strings:
string = string.lower()
return strings
But this implementation is not working, however when using the range funtion and I iterate using an index:
def lower_list(strings):
for i in range(len(strings)):
strings[i] = strings[i].lower()
return strings
I do get every element on my list converted to lowercase:
> print(lower_list(mylist))
['oh brother where art thou', 'hello dolly', 'monsters inc', 'fargo']
But with the first implementation I get the original list with Uppercase values, am I missing something important in how the for loop works?
In the first case, all you are doing is storing the lowercase value in a variable, but the list is untouched.
In the second case, you are actually updating the value in the list at that index.
You can also use a lambda function here:
def lower_list(strings):
return list(map(lambda x: x.replace(x, x.lower()), strings))
List comprehension is the easiest and the best:
def lower_list(strings):
return [string.lower() for string in strings]
The reason the first one does not work is that it is not actually modifying the value inside of the list, rather it is just affecting a copy of the value in the list. When you use the index-based function, it modifies the list itself.
def lower_list(strings):
for string in strings:
index_of_string = strings.index(string)
string = string.lower()
strings[index_of_string] = string
return strings
If you want the first one to work, maybe you can try something like that, but thats a bad way of doing it, just showing it as an example so maybe you'll understand better. You need the index of that string so you can replace it in the list. In your first attempt, you do not replace anything in the list.

python string to list (special list)

I'm trying to get this string into list, how can i do that pleas ?
My string :
x = "[(['xyz1'], 'COM95'), (['xyz2'], 'COM96'), (['xyz3'], 'COM97'), (['xyz4'], 'COM98'), (['xyz5'], 'COM99'), (['xyz6'], 'COM100')]"
I want to convert it to a list, so that:
print(list[0])
Output : (['xyz1'], 'COM95')
If you have this string instead of a list, that presumes it is coming from somewhere outside your control (otherwise you'd just make a proper list). If the string is coming from a source outside your program eval() is dangerous. It will gladly run any code passed to it. In this case you can use ast.liter_eval() which is safer (but make sure you understand the warning on the docs):
import ast
x = "[(['xyz1'], 'COM95'), (['xyz2'], 'COM96'), (['xyz3'], 'COM97'), (['xyz4'], 'COM98'), (['xyz5'], 'COM99'), (['xyz6'], 'COM100')]"
l = ast.literal_eval(x)
Which gives an l of:
[(['xyz1'], 'COM95'),
(['xyz2'], 'COM96'),
(['xyz3'], 'COM97'),
(['xyz4'], 'COM98'),
(['xyz5'], 'COM99'),
(['xyz6'], 'COM100')]
If the structure is uniformly a list of tuples with a one-element list of strings and an individual string, you can manually parse it using the single quote as a separator. This will give you one string value every other component of the split (which you can access using a striding subscript). You can then build the actual tuple from pairing of two values:
tuples = [([a],s) for a,s in zip(*[iter(x.split("'")[1::2])]*2)]
print(tuples[0])
(['xyz1'], 'COM95')
Note that this does not cover the case where an individual string contains a single quote that needed escaping
You mean convert list like string into list? Maybe you can use eval().
For example
a="[1,2,3,4]"
a=eval(a)
Then a become a list
to convert as list use x = eval(x)
print(list[0]) will give you an error because list is a python builtin function
you should do print(x[0]) to get what you want

can't understand how assigning characters in string to list through list slicing works in following piece of code

I can't understand how string is assigned to the list
def convert(string):
list1 = []
list1[:0] = string
return list1
# Driver code
str1 = "ABCD"
print(convert(str1))
As it looks its a way of converting a string to a list, you can do it like
list(string)
but this is also quite interesting as , it takes whatever is the input the append it in the start of the list,
from python docs list insertion
list1[0:0] inserts the iterable to before the first element of the list, if you slice the list to go up to zero elemen it gives you an empty list

Efficient way to convert a list of one string to a string and perform split operation

I have a list which contains a string shown below. I have defined mylist in the global space as a string using "".
mylist = ""
mylist = ["1.22.43.45"]
I get an execution error stating that the split operation is not possible as it is being performed on a list rather than the string.
mylist.rsplit(".",1)[-1]
I tried to resolve it by using the following code:
str(mylist.rsplit(".",1)[-1]
Is this the best way to do it? The output I want is 45. I am splitting the string and accessing the last element. Any help is appreciated.
mylist=["1.22.43.45"]
newstring = mylist[0].rsplit(".",1)[-1]
First select the element in your list then split then choose the last element in the split
Just because you assigned mylist = "" first, doesn't mean it'll cast the list to a string. You've just reassigned the variable to point at a list instead of an empty string.
You can accomplish what you want using:
mylist = ["1.22.43.45"]
mylist[-1].rsplit('.', 1)[-1]
Which will get the last item from the list and try and perform a rsplit on it. Of course, this won't work if the list is empty, or if the last item in the list is not a string. You may want to wrap this in a try/except block to catch IndexError for example.
EDIT: Added the [-1] index to the end to grab the last list item from the split, since rsplit() returns a list, not a string. See DrBwts' answer
You can access the first element (the string, in your case) by the index operator []
mylist[0].rsplit(".", 1)[-1]

Python Replace Character In List

I have a Python list that looks like the below:
list = ['|wwwwwwwwadawwwwwwwwi', '|oooooooocFcooooooooi']
I access the letter in the index I want by doing this:
list[y][x]
For example, list[1][10] returns F.
I would like to replace F with a value. Thus changing the string in the list.
I have tried list[y][x] = 'o' but it throws the error:
self.map[y][x] = 'o'
TypeError: 'str' object does not support item assignment
Can anybody help me out? Thanks.
As #Marcin says, Python strings are immutable. If you have a specific character/substring you want to replace, there is string.replace. You can also use lists of characters instead of strings, as described here if you want to support the functionality of changing one particular character.
If you want something like string.replace, but for an index rather than a substring, you can do something like:
def replaceOneCharInString(string, index, newString):
return string[:index] + newString + string[index+len(newString):]
You would need to do some length checking, though.
Edit: forgot string before the brackets on string[index+len(newString):]. Woops.
Since python strings are immutable, they cannot be modified. You need to make new ones. One way is as follows:
tmp_list = list(a_list[1])
tmp_list[10] = 'o' # simulates: list[1][10]='o'
new_str = ''.join(tmp_list)
#Gives |oooooooococooooooooi
# substitute the string in your list
a_list[1] = new_str
As marcin says, strings are immutable in Python so you can not assign to individual characters in an existing string. The reason you can index them is that thay are sequences. Thus
for c in "ABCDEF":
print(c)
Will work, and print each character of the string on a separate line.
To achieve what you want you need to build a new string.For example, here is a brute force approach to replacing a single character of a string
def replace_1(s, index, c)
return s[:index] + c + s[index+1:]
Which you can use thus:
self.map[y] = replace_1(self.map[y], x, 'o')
This will work because self.map is list, which is mutable by design.
Let use L to represent the "list" since list is a function in python
L= ['|wwwwwwwwadawwwwwwwwi', '|oooooooocFcooooooooi']
L[1]='|oooooooococooooooooi'
print(L)
Unfortunately changing a character from an object (in this case) is not supported. The proper way would be to remove the object and add a new string object.
Output
['|wwwwwwwwadawwwwwwwwi', '|oooooooococooooooooi']

Categories