Replace one string in a list of strings - python

I have a list of strings.
If one of the strings (e.g. at index 5) is the empty string, I want to replace it with "N".
How do I do that? The naive method (for a java programmer) does not work:
string_list[5] = "N"
gives
'str' object does not support item assignment
(string_list originally came from a .csv-file- that is why it might contain empty strings.)

Your error seems to indicate that your string_list is not a list of string but a real string (that doesn't support assignement because a string is immutable).
If your string_list was a real list of strings, like this for example : string_list = ["first", "second", "", "fourth"], then you will be able to do string_list[2] = "third" to obtain string_list = ["first", "second", "third", "fourth"].
If you need to automatically detect where an empty string is located in your list, try with index :
string_list[string_list.index("")] = "replacement string"
print string_list
>>> ["first", "second", "replacement string", "fourth"]

You say you have a list of strings but from you error it looks like you're trying to index a string
l = ["a", "b", "", "c"]
Is a list of strings.
l = ["N" if not x else x for x in l]
Is a list of strings with empty strings replaced with "N"

Try this:
>>> s = 'abc de'
>>> s.replace(' ', 'N')
'abcNde'
As mentioned by the others, it sounds like string_list is actually a string itself, meaning that you can't use assignment to change a character.

In python work with lists and convert them to strings when need be.
>> str = list("Hellp")
>> str
['H', 'e', 'l', 'l', 'p']
>> str[4] = 'o'
>> str
['H', 'e', 'l', 'l', 'o']
TO make it a string use
>> "".join(str)
'Hello World'
Python strings are immutable and they cannot be modified.
Or you could use List Comprehensions.
Some thing like:
>> myStr = ['how', 'are', 'yew', '?']
>> myStr = [w.replace('yew', 'you') for w in myStr]

The following example iterates through lists of lists (sublists), in order to replace a string, a word:
myoldlist=[['aa bbbbb'],['dd myword'],['aa myword']]
mynewlist=[]
for i in xrange(0,3,1):
mynewlist.append([x.replace('myword', 'new_word') for x in myoldlist[i]])
print mynewlist
# ['aa bbbbb'],['dd new_word'],['aa new_word']

Related

Python string to list per character

Good day I just want to understand the logic behind this code
lst = []
word = "ABCD"
lst[:0] = word
print(lst)
OUTPUT: ['A', 'B', 'C', 'D'] why not ['ABCD'] how?
for i in word: # this code I understand it's looping through the string
lst.append(i) # then appending to list
but the first code above I don't get the logic.
lst[:0] = ... is implemented by lst.__setitem__(slice(0, None, 0), ...), where ... is an arbitrary iterable.
The resulting slice is the empty list at the beginning of lst (though in this case, it doesn't really matter since lst is empty), so each element of ... is inserted into lst, starting at the beginning.
You can see this starting with a non-empty list.
>>> lst = [1,2,3]
>>> word = "ABCD"
>>> lst[:0] = word
>>> lst
['A', 'B', 'C', 'D', 1, 2, 3]
To get lst == ['ABCD'], you need to make the right-hand side an iterable containing the string:
lst[:0] = ('ABCD', ) # ['ABCD'] would also work.
Actually it's a well known way to convert string to a list character by character
you can find here -> https://www.geeksforgeeks.org/python-program-convert-string-list/
if you wanna try to get your list element like 'ABCD' then try
lst[:0] = [word,]
by doing that you specify that you need whole word as an element

How do i remove a string from a list if it DOES NOT contain certain characters in Python

I am working on a list filter. This is as far as I've gone. I would like to remove every string that doesn't contain H, L OR C. So far this is my attemp
input_list = input("Enter The Results(leave a space after each one):").split(' ')
for i in input_list:
if 'H'not in i or 'L' not in i or 'C' not in i:
Use this pythonic code
input_list = input("Enter The Results(leave a space after each one):").split(' ') # this is the input source
after_removed = [a for a in input_list if ('H' not in a and 'L' not in a and 'C' not in a)] # this is the after removed 'H', 'L', and 'C' from the input_list
Using list comprehension, you can make python easier and faster
If you don't believe, just try it for yourself :D
For clarity, you can use a function
def contains_invalid_character(my_string):
return 'H' in my_string or 'L' in my_string or 'C' in my_string
# To be more pythonic, you can use the following
# return next((True for letter in ("H", "L", "C") if letter in my_string), False)
results = []
for i in input_list:
if not contains_invalid_character(i):
results.append(i)
# Or to be more pythonic
# results = [i for i in input_list if not contains_invalid_character(i)]

Python Append Function?

The function will return a list containing all the letters found in both strings. All the letters returned should be lowercase.
There should be no duplicate letters in the list returned by your function.
Example:
string_scramble('GraSS', 'grilled cheese') should return: ['g','r','s']
def string_scramble(string_one, string_two):
string_one = "hello there"
string_two = "welcome to town"
a = list(set(string_one) & set(string_two))
for i in a:
print(i)
a = set(string_one).union(string_two)
You could use a lambda expression that solves your question:
scrambler = lambda str1, str2: list(set(str1.lower())&set(str2.lower()))
Just try
scrambler('GraSS','grilled cheese')
def string_scramble(string_one, string_two):
new_list = []
for letter in sorted(set(string_one.lower())):
if letter in sorted(set(string_two.lower())):
new_list.append(letter)
return new_list
print(string_scramble('grass', 'grilled cheese'))
output:
['g', 'r', 's']
I added .lower() because it appears as if you want to ignore the case based on your question. In Python, we can simply convert the entire string to lower case. The set function will return the output that you are looking for.
Also of interest, I used sorted here so that you can keep the strings in order in the set, because a set is generally unordered.
string_one = "hello there"
string_two = "welcome to town"
set(string_one.lower()) & set(string_two.lower())
->>> {'t', 'l', 'e', ' ', 'o'}

get an element out of a string python

I am trying to use line.strip() and line.split() to get an element out of a file, but this always gives me a list of string, does line.split() always return a string? how can I just get a list of elements instead of a list of 'elements'?
myfile = open('myfile.txt','r')
for line in myfile:
line_strip = line.strip()
myline = line_strip.split(' ')
print(myline)
So my code gives me ['hello','hi']
I want to get a list out of the file look likes[hello,hi]
[2.856,9.678,6.001] 6 Mary
[8.923,3.125,0.588] 7 Louis
[7.122,9.023,4,421] 16 Ariel
so when I try
list = []
list.append((mylist[0][0],mylist[0][1]))
I actually want a list = [(2.856,9.678),(8.923,3.123),(7.122,9.023)]
but it seems this mylist[0][0] refers to '[' in my file
my_string = 'hello'
my_list = list(my_string) # ['h', 'e', 'l', 'l', 'o']
my_new_string = ''.join(my_list) # 'hello'
I think you are looking for this
>>> print("[{}]".format(", ".join(data)))
[1, 2, 3]
To address your question, though
this always gives me a list of string,
Right. As str.split() should do.
does line.split() always return a string?
Assuming type(line) == str, then no, it returns a list of string elements from the split line.
how can I just get a list of elements instead of a list of 'elements'?
Your "elements" are strings. The ' marks are only Python's repr of a str type.
For example...
print('4') # 4
print(repr('4')) # '4'
line = "1,2,3"
data = line.split(",")
print(data) # ['1', '2', '3']
You can cast to a different data-type as you wish
print([float(x) for x in data]) # [1.0, 2.0, 3.0]
For what you posted, use a regex:
>>> s="[2.856,9.678,6.001] 6 Mary"
>>> import re
>>> [float(e) for e in re.search(r'\[([^\]]+)',s).group(1).split(',')]
[2.856, 9.678, 6.001]
For all the lines you posted (and this would be similar to a file) you might do:
>>> txt="""\
... [2.856,9.678,6.001] 6 Mary
... [8.923,3.125,0.588] 7 Louis
... [7.122,9.023,4,421] 16 Ariel"""
>>> for line in txt.splitlines():
... print [float(e) for e in re.search(r'\[([^\]]+)',line).group(1).split(',')]
...
[2.856, 9.678, 6.001]
[8.923, 3.125, 0.588]
[7.122, 9.023, 4.0, 421.0]
You would need to add error code to that (if the match fails for instance) but this is the core of what you are looking for.
BTW: Don't use list as a variable name. You will overwrite the list function and have confusing errors in the future...
line.split() returns a list of strings.
For example:
my_string = 'hello hi'
my_string.split(' ') is equal to ['hello', 'hi']
To put a list of strings, like ['hello', 'hi] back together, use join.
For example, ' '.join(['hello', 'hi']) is equal to 'hello hi'. The ' ' specifies to put a space between all the elements in the list that you are joining.

Python Concatenate string with all members of a list and display each display result separated by commas

I'm trying to do something like a "conjugator".
Say I have a list of endings:
endings = ['o', 'es', 'e', 'emos', 'eis', 'em']
and I have a verb root as a string:
root = "com"
The way I thought of doing this is:
for ending in endings:
print root + ending
which outputs:
como
comes
come
comemos
comeis
comem
But my desired result is:
como, comes, come, comemos, comeis, comem
How can I achieve exactly this (and with no quotes around each of the resulting items, and no comma after the last item)?
You need a list comprehension and str.join(). From the documentation:
str.join(iterable)
Return a string which is the concatenation of the
strings in the iterable iterable. The separator between elements is
the string providing this method.
>>> root = "com"
>>> endings = ['o', 'es', 'e', 'emos', 'eis', 'em']
>>> verbs = [root + ending for ending in endings]
>>> print ", ".join(verbs)
como, comes, come, comemos, comeis, comem

Categories

Resources