Getting data outside of a list in python - python

I have list with one item in it, then I try to dismantle, & rebuild it.
Not really sure if it is the 'right' way, but for now it will do.
I tried using replace \ substitute, other means of manipulating the list, but it didn't go too far, so this is what I came up with:
This is the list I get : alias_account = ['account-12345']
I then use this code to remove the [' in the front , and '] from the back.
NAME = ('%s' % alias_account).split(',')
for x in NAME:
key = x.split("-")[0]
value = x.split("-")[1]
alias_account = value[:-2]
alias_account1 = key[2:]
alias_account = ('%s-%s') % (alias_account1, alias_account)
This works beautifully when running print alias_account.
The problem starts when I have a list that have ['acc-ount-12345'] or ['account']
So my question is, how to include all of the possibilities?
Should I use try\except with other split options?
or is there more fancy split options ?

To access a single list element, you can index its position in square brackets:
alias_account[0]
To hide the quotes marking the result as a string, you can use print():
print(alias_account[0])

Related

.replace only replaces last character in list

title = 'Example####+||'
blacklisted_chars = ['#','|','#','+']
for i in blacklisted_chars:
convert = title.replace(i, '')
print(convert)
# Example####||
I want to remove all blacklisted characters in a list and replace them with '', however when the code is run only the final 'blacklisted_char' is replaced within the print statement
I am wondering how I would make it that all characters are replaced and only 'Example' is printed
Strings are immutable in python. You assign a new string with
convert = title.replace(i, '')
title remains unchanged after this statement. convert is an entirely new string that is missing i.
On the next iteration, you replace a different value of i, but still from the original title. So in the end it looks like you only ran
convert = title.replace('+', '')
You have two very similar options, depending on whether you want to keep the original title around or not.
If you do, make another reference to it, and keep updating that reference with the results, so that each successive iteration builds on the result of the previous removal:
convert = title
for i in blacklisted_chars:
convert = convert.replace(i, '')
print(convert)
If you don't care to retain the original title, use that name directly:
for i in blacklisted_chars:
title = title.replace(i, '')
print(title)
You can achieve a similar result without an explicit loop using re.sub:
convert = re.sub('[#|#+]', '', title)
Try this :
title = 'Example####+||'
blacklisted_chars = ['#','|','#','+']
for i in blacklisted_chars:
title = title.replace(i, '')
print(title)
Explanation: Since you were storing the result of title.replace in the convert variable, every iteration it was being overwritten. What you need is to apply replace to the result of the previous iteration, which can be the variable with the original string or another variable containing a copy of it if you want to keep the original value unchanged.
P.S.: strings are iterables so you can also achieve the same results with something like this:
blacklisted_chars = '#|#+'

Change a list separator delimiter to another (python)

I need help using Python.
Supposing I have the list [22,23,45].
Is it possible to get an output like this: [22;23:45] ?
It's possible to change the delimiters if you display your list as a string. You can then use the join method. The following example will display your list with ; as a delimiter:
print(";".join(my_list))
This will only work if your list's items are string, by the way.
Even if you have more than one item
str(your_list[:1][0])+";" + ":".join(map(str,your_list[1:])) #'22;23:45'
Not sure why you want to wrap in the list but if you do just wrap around the above string in list()
my list which was [22,23,45] returned [;2;2;,; ;2;3;,; ;4;5;,] for both methods.
To bring more information, I have a variable:
ID= [elements['id'] for elements in country]
Using a print (ID), I get [22,23,45] so I suppose that the list is already to this form.
Problem is: I need another delimiters because [22,23,45] corresponds to ['EU, UK', 'EU, Italy', 'USA, California'].
The output I wish is [22,23,45] --> ['EU, UK'; 'EU, Italy'; 'USA, California']
I don't know if it's clearer but hope it could help
Try this I don't know exactly what do You want?
first solution:
list = [22,23,45]
str = ""
for i in list:
str += "{}{}".format(i, ";")
new_list=str[:-len(";")]
print(new_list)
and this is second solution
list = [22,23,45]
print(list)
list=str(list)
list=list.split(",")
list=";".join(list)
print(list)

Python: Removing characters from a string and then returning it

For example, given a list of strings prices = ["US$200", "CA$80", "GA$500"],
I am trying to only return ["US", "CA", "GA"].
Here is my code - what am I doing wrong?
def get_country_codes(prices):
prices = ""
list = prices.split()
list.remove("$")
"".join(list)
return list
Since each of the strings in the prices argument has the form '[country_code]$[number]', you can split each of them on '$' and take the first part.
Here's an example of how you can do this:
def get_country_codes(prices):
return [p.split('$')[0] for p in prices]
So get_country_codes(['US$200', 'CA$80', 'GA$500']) returns ['US', 'CA', 'GA'].
Also as a side note, I would recommend against naming a variable list as this will override the built-in value of list, which is the type list itself.
There are multiple problems with your code, and you have to fix all of them to make it work:
def get_country_codes(prices):
prices = ""
Whatever value your caller passed in, you're throwing that away and replacing it with "". You don't want to do that, so just get rid of that last line.
list = prices.split()
You really shouldn't be calling this list list. Also, split with no argument splits on spaces, so what you get may not be what you want:
>>> "US$200, CA$80, GA$500".split()
['US$200,', 'CA$80,', 'GA$500']
I suppose you can get away with having those stray commas, since you're just going to throw them away. But it's better to split with your actual separators, the ', '. So, let's change that line:
prices = prices.split(", ")
list.remove("$")
This removes every value in the list that's equal to the string "$". There are no such values, so it does nothing.
More generally, you don't want to throw away any of the strings in the list. Instead, you want to replace the strings, with strings that are truncated at the $. So, you need a loop:
countries = []
for price in prices:
country, dollar, price = price.partition('$')
countries.append(country)
If you're familiar with list comprehensions, you can rewrite this as a one-liner:
countries = [price.partition('$')[0] for price in prices]
"".join(list)
This just creates a new string and then throws it away. You have to assign it to something if you want to use it, like this:
result = "".join(countries)
But… do you really want to join anything here? It sounds like you want the result to be a list of strings, ['US', 'CA', 'GA'], not one big string 'USCAGA', right? So, just get rid of this line.
return list
Just change the variable name to countries and you're done.
Since your data is structured where the first two characters are the county code you can use simple string slicing.
def get_country_codes(prices):
return [p[:2] for p in prices]
You call the function sending the prices parameter but your first line initialize to an empty string:
prices = ''
I would also suggest using the '$' character as the split character, like:
list = prices.split('$')
try something like this:
def get_country_codes(prices):
list = prices.split('$')
return list[0]

how can I add mark every two index in String

def Change(_text):
L = len(_text)
_i = 2
_text[_i] = "*"
_i += 2
print(_text)
How can I add a mark e.g:* every two Index In String
Why are you using _ in your variables? If it is for any of these reasons then you are OK, if it is a made up syntax, try not to use it as it might cause unnecessary confusion.
As for your code, try:
def change_text(text):
for i in range(len(text)):
if i % 2 == 0: # check if i = even (not odd)
print(text[:i] + "*" + text[i+1:])
When you run change_text("tryout string") the output will look like:
*ryout string
tr*out string
tryo*t string
tryout*string
tryout s*ring
tryout str*ng
tryout strin*
If you meant something else, name a example input and wished for output.
See How to create a Minimal, Complete, and Verifiable example
PS: Please realize that strings are immutable in Python, so you cannot actually change a string, only create new ones from it.. if you want to actually change it you might be better of saving it as a list for example. Like they have done here.
Are you trying to separate every two letters with an asterix?
testtesttest
te*st*te*st*te*st
You could do this using itertools.zip_longest to split the string up, and '*'.join to rebuild it with the markers inserted
from itertools import zip_longest
def add_marker(s):
return '*'.join([''.join(x) for x in zip_longest(*[iter(s)]*2, fillvalue='')])

Python Lists -Syntax for '['

I need to declare certain values in List.
Values looks like this:
["compute","controller"], ["compute"] ,["controller"]
I know the List syntax in python is
example = []
I am not sure how I will include square brackets and double quotes in the List.
Could anyone please help.
I tried the following:
cls.node = ["\["compute"\]","\["controller"\]"]
cls.node = ["[\"compute\"]","[\"controller\"]"]
Both did not work.
I think you mean list not dictionary because that is the syntax of a list:
You can simply do it using the following format '"Hello"':
cls.node = ['["compute"]','["controller"]']
cls.node = ['["compute"]','["controller"]']
Demo:
s = ['["hello"]', '["world"]']
for i in s:
print i
[OUTPUT]
["hello"]
["world"]

Categories