Append a portion of a string to a list - python

I was wondering how one can append a portion of a string to a list? Is there an option of both appending based on the position of characters in the string, and another option that is able to take a specific character of interest? For instance, If I had the string "2 aikjhakihaiyhgikjewh", could I not only append the part of the string that was in positions 3-4 but also append the "2" as well? I'm a beginner, so I'm still kinda new to this python thing. Thanks.

You can use slicing to reference a portion of a string like this:
>>> s = 'hello world'
>>> s[2:5]
'llo'
You can append to a list using the append method:
>>> l = [1,2,3,4]
>>> l.append('Potato')
>>> l
[1, 2, 3, 4, 'Potato']
Best way to learn this things in python is to open an interactive shell and start typing commands on it. I suggest ipython as it provides autocomplete which is great for exploring objects methods and properties.

You can append a portion of a string to a list by using the .append function.
List = []
List.append("text")
To append several parts of the string you can do the following:
List = []
String = "2 asdasdasd"
List.append(String[0:2] + String[3:5])
This would add both sections of the string that you wanted.

Use slicing to accomplish what you are looking for:
mystr = "2 aikjhakihaiyhgikjewh"
lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
print lst
This runs as:
>>> mystr = "2 aikjhakihaiyhgikjewh"
>>> lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
>>> print lst
['2', 'i', 'k']
>>>
Slicing works by taking certain parts of an object:
>>> mystr
'2 aikjhakihaiyhgikjewh'
>>> mystr[0]
'2'
>>> mystr[-1]
'h'
>>> mystr[::-1]
'hwejkighyiahikahjkia 2'
>>> mystr[:-5]
'2 aikjhakihaiyhgi'
>>>

You are describing 2 separate operations: slicing a string, and extending a list. Here is how you can put the two together:
In [26]: text = "2 aikjhakihaiyhgikjewh"
In [27]: text[0], text[3:5]
Out[27]: ('2', 'ik')
In [28]: result = []
In [29]: result.extend((text[0], text[3:5]))
In [30]: result
Out[30]: ['2', 'ik']

Related

How to add a word before the last word in list?

Hello I'm new to this programming language
I wanted to add the word 'and' before the last item in my list.
For example:
myList = [1,2,3,4]
If I print it the output must be like:
1,2,3 and 4
Here is one way, but I have to convert the int's to strings to use join:
myList = [1,2,3,4]
smyList = [str(n) for n in myList[:-1]]
print(",".join(smyList), 'and', myList[-1])
gives:
1,2,3 and 4
The -1 index to the list gives the last (rightmost) element.
This may not be the most elegant solution, but this is how I would tackle it.
define a formatter function as follows:
def format_list(mylist)
str = ''
for i in range(len(mylist)-1):
str.append(str(mylist[i-1]) + ', ')
str.append('and ' + str(mylist[-1]))
return str
then call it like this
>>> x = [1,2,3,4]
>>> format_list(x)
1, 2, 3, and 4
You can also use string formating:
l = [1,2,3,4]
print("{} and {}".format(",".join(str(i) for i in l[:-1]), l[-1]))
#'1,2,3 and 4'
Using join (to join list elements) and map(str,myList) to convert all integers inside list to strings
','.join(map(str,myList[:-1])) + ' and ' + str(myList[-1])
#'1,2,3 and 4'
Your question is misleading, if you are saying "How to add a word before the last word in list?" it means you want to add 'and' string before last item in the list , while many people are giving answer using .format() method , You should specify you want 'and' for printing or in list for further use of that result :
Here is list method according to your question :
myList = [1,2,3,4]
print(list((lambda x,y:(x+['and']+y))(myList[:-1],myList[-1:])))
output:
[1, 2, 3, 'and', 4]

Python integers with trailing 'L' in a list [duplicate]

So I have a list:
['x', 3, 'b']
And I want the output to be:
[x, 3, b]
How can I do this in python?
If I do str(['x', 3, 'b']), I get one with quotes, but I don't want quotes.
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".
This is simple code, so if you are new you should understand it easily enough.
mylist = ["x", 3, "b"]
for items in mylist:
print(items)
It prints all of them without quotes, like you wanted.
Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
If you are using Python3:
print('[',end='');print(*L, sep=', ', end='');print(']')
Instead of using map, I'd recommend using a generator expression with the capability of join to accept an iterator:
def get_nice_string(list_or_iterator):
return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"
Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.
You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.
lst = ['x', 3, 'b']
print str(lst).translate(None, "'")
# [x, 3, b]
If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:
import string
print string.translate(str(lst), None, "'")
Using the string.translate() function will also work in 2.6+, so using it might be preferable.
Here's an interactive session showing some of the steps in #TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)
Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.
>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'
Using .format for string formatting,
mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))
Output:
[x, 3, b]
Explanation:
map is used to map each element of the list to string type.
The elements are joined together into a string with , as separator.
We use [ and ] in the print statement to show the list braces.
Reference:
.format for string formatting PEP-3101
I was inspired by #AniMenon to write a pythonic more general solution.
mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))
It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format.
For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f
mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))
The output is quite decent:
[1.85, -6.33, 4000.21]

How can i remove all extra characters from list of strings to convert to ints

Hi I'm pretty new to programming and Python, and this is my first post, so I apologize for any poor form.
I am scraping a website's download counts and am receiving the following error when attempting to convert the list of string numbers to integers to get the sum.
ValueError: invalid literal for int() with base 10: '1,015'
I have tried .replace() but it does not seem to be doing anything.
And tried to build an if statement to take the commas out of any string that contains them:
Does Python have a string contains substring method?
Here's my code:
downloadCount = pageHTML.xpath('//li[#class="download"]/text()')
downloadCount_clean = []
for download in downloadCount:
downloadCount_clean.append(str.strip(download))
for item in downloadCount_clean:
if "," in item:
item.replace(",", "")
print(downloadCount_clean)
downloadCount_clean = map(int, downloadCount_clean)
total = sum(downloadCount_clean)
Strings are not mutable in Python. So when you call item.replace(",", ""), the method returns what you want, but it is not stored anywhere (thus not in item).
EDIT :
I suggest this :
for i in range(len(downloadCount_clean)):
if "," in downloadCount_clean[i]:
downloadCount_clean[i] = downloadCount_clean[i].replace(",", "")
SECOND EDIT :
For a bit more simplicity and/or elegance :
for index,value in enumerate(downloadCount_clean):
downloadCount_clean[index] = int(value.replace(",", ""))
For simplicities sake:
>>> aList = ["abc", "42", "1,423", "def"]
>>> bList = []
>>> for i in aList:
... bList.append(i.replace(',',''))
...
>>> bList
['abc', '42', '1423', 'def']
or working just with a single list:
>>> aList = ["abc", "42", "1,423", "def"]
>>> for i, x in enumerate(aList):
... aList[i]=(x.replace(',',''))
...
>>> aList
['abc', '42', '1423', 'def']
Not sure if this one breaks any python rules or not :)

Python List Replace [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Python and Line Breaks
In Python I know that when your handling strings you can use "replace" to replace a certain character in a string. For example:
h = "2,3,45,6"
h = h.replace(',','\n')
print h
Returns:
2
3
45
6
Is there anyway to do this with a list? For example replace all the "," in a list with "\n"?
A list like:
h = ["hello","goodbye","how are you"]
"hello"
"goodbye"
"how are you"
And the Script should output something like this:
Any suggestions would be helpful!
Looking at your example and desire, you can use the str.join and this is probably what you want
>>> h
['2', '3', '45', '6']
>>> print '\n'.join(str(i) for i in h)
2
3
45
6
similarly for your second example
>>> h = ["hello","goodbye","how are you"]
>>> print '\n'.join(str(i) for i in h)
hello
goodbye
how are you
If you really wan't the quotation mark for strings you can use the following
>>> h = ["hello","goodbye","how are you"]
>>> print '\n'.join('"{0}"'.format(i) if isinstance(i,str) else str(i) for i in h)
"hello"
"goodbye"
"how are you"
>>>
You could use list comprehension for that:
>>> search = 'foo'
>>> replace = 'bar'
>>> lst = ['my foo', 'foo', 'bip']
>>> print [x.replace(search, replace) for x in lst]
['my bar', 'bar', 'bip']
In a list like your h = [2,5,6,8,9], there really are no commas to replace in the list itself. The list contains the items 2, 5 and so on, the commas are merely part of the external representation to make it easier to separate the items visually.
So, to generate some output form from the list but without the commas, you can use any number of techniques. For instance, to join them all up into a single string without commas, use:
"".join([str(x) for x in h])
This will evaluate to 25689.
for each in h: print each
In 3.x:
for each in h: print(each)
A list is simply a representation of data. You can only affect the way it looks in the output.
You can replace the ',' in the string because the ',' is part of the string itself but you cannot replace the ',' in a list because it is not an item in the list rather it is what is used by python for delineating different items in such a list together with the opening and closing square brackets. It is just like asking if you could replace the '"' used in creating the string. On the other hand if the ',' is an item in the list and you want to replace it with a newline item then you could use list comprehensions like:
['\n' if x=="," else x for x in yourlist]
or if you want to print each item on a single line you could use:
for item in list:
print item

How to "properly" print a list?

So I have a list:
['x', 3, 'b']
And I want the output to be:
[x, 3, b]
How can I do this in python?
If I do str(['x', 3, 'b']), I get one with quotes, but I don't want quotes.
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".
This is simple code, so if you are new you should understand it easily enough.
mylist = ["x", 3, "b"]
for items in mylist:
print(items)
It prints all of them without quotes, like you wanted.
Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
If you are using Python3:
print('[',end='');print(*L, sep=', ', end='');print(']')
Instead of using map, I'd recommend using a generator expression with the capability of join to accept an iterator:
def get_nice_string(list_or_iterator):
return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"
Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.
You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.
lst = ['x', 3, 'b']
print str(lst).translate(None, "'")
# [x, 3, b]
If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:
import string
print string.translate(str(lst), None, "'")
Using the string.translate() function will also work in 2.6+, so using it might be preferable.
Here's an interactive session showing some of the steps in #TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)
Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.
>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'
Using .format for string formatting,
mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))
Output:
[x, 3, b]
Explanation:
map is used to map each element of the list to string type.
The elements are joined together into a string with , as separator.
We use [ and ] in the print statement to show the list braces.
Reference:
.format for string formatting PEP-3101
I was inspired by #AniMenon to write a pythonic more general solution.
mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))
It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format.
For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f
mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))
The output is quite decent:
[1.85, -6.33, 4000.21]

Categories