Remove an element from a str - python

I have a list in which I add elements like this:
listA.append('{:<30s} {:>10s}'.format(element, str(code)))
so listA looks like this:
Paris 75
Amsterdam 120
New York City 444
L.A 845
I would like, now from this listA, to add elements to a "listB" list, without the code. I would like to do this:
for i in listA:
listB.append(i - str(code)) #that's what i want to do. The code is not good
and I want the listB to look like this:
Paris
Amsterdam
New York City
L.A
and only using listA and without having access to 'element' and 'code'
Can someone can help me ?

You can use regex for that
import re
for i in listA:
listB.append(re.sub(r"\W+\d+", "", i))
This will remove the code that is numbers and the spaces before it.

Try this:
import re
listB = [re.sub('\d+', '', x).strip() for x in listA]
print(listB)
Output:
['Paris', 'Amsterdam', 'New York City', 'L.A']

This seems to work for me
listB=[]
for i in listA:
listB.append(listA[0][:len(element)])
print(listB)

You can try the following:
listB = [element.rsplit(' ', maxsplit=1)[0].rstrip() for element in listA]
rsplit(' ', maxsplit=1) means you will split the element of listA once at first space from the right side. Additional rstrip() will get rid of the other spaces from the right side.

How about to use re.sub? And instead of using for in it would be better to map functional style or [for in] list comprehension:
import re
listB = list(map(lambda x: re.sub(r"\s+\d+", "", x), listA))
or, even better
import re
listB = [re.sub(r"\s+\d+", "", x) for x in listA]
A little about regex:
re.sub - is a function what searches an removes all occurrences of first argument to second in third one
r"\s+\d+" - is a 'raw' string literal with regex inside
\s+ - one or more whitespaces (\t\n\r etc)
\d+ - one or more digits (\d is an allias for [0-9])
For more information about regex use this documentation page

Easiest way without any new libraries.
You can create a variable with 40 spaces(because of 40 spaces in the format clause). eg: space_var = " "
Then use the following code to extract element from listA:
listB=[]
for i in listA:
listB.append(listA[0].rsplit(space_var,1)[0])

Related

How to print a string which is a name with two words in reverse order without commas and unnecessary spaces? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have to write a function that takes a string of full names and prints it in reverse order. It also removes unnecessary spaces and commas. Some of the expected output is as follow:
- >>> reverse_name("Techie, Teddy")
'Teddy Techie'
>>> reverse_name("Scumble, Arnold")
'Arnold Scumble'
>>> reverse_name("Fortunato,Frank")
'Frank Fortunato'
>>> reverse_name("von Grünbaumberger, Herbert")
'Herbert von Grünbaumberger'
>>> reverse_name(" Duck, Donald ")
'Donald Duck'
>>> reverse_name("X,")
'X'
>>> reverse_name(",X")
'X'
>>> reverse_name(" , Y ")
'Y'.
I wrote the following code.
def main():
name=input()
reverse_name(name)
print(reverse_name(name))
def reverse_name(string1):
i = 0
for index in string1:
if index != ",":
i += 1
else:
last = string1[i + 1:]
first = string1[0:i]
result = last + " " + first
return result
if __name__ == "__main__":
main()
p.s: I must implement a function that takes a string as a parameter and returns a string. The input will also contain a comma which the output will not print.
You could combine split and join after having inverted the output of split:
def reverse_name(s):
return ' '.join([e.strip() for e in s.split(', ')][::-1])
>>> reverse_name('Techie, Teddy')
'Teddy Techie'
>>> reverse_name(' Duck, Donald ')
'Donald Duck'
Here is another option using the re module:
def reverse_name(s):
return re.sub(r'\s*(.+),\s*(.*\S)\s*', r'\2 \1', s)
if a comma is guaranty to always be there simply using string1.split(",") will give you a list of the separate words in the string, and simple filter the empty one and removing the trailing white spaces with .strip will do the trick
>>> def reverse_name(text):
return " ".join( w for w in map(str.strip,reversed(text.split(","))) if w)
# ^removing trailing white space ^filter empty ones
>>> reverse_name("Techie, Teddy")
'Teddy Techie'
>>> reverse_name("Scumble, Arnold")
'Arnold Scumble'
>>> reverse_name("von Grünbaumberger, Herbert")
'Herbert von Grünbaumberger'
>>> reverse_name("Fortunato,Frank")
'Frank Fortunato'
>>> reverse_name("X,")
'X'
>>> reverse_name(",X")
'X'
>>> reverse_name(" , Y ")
'Y'
>>> reverse_name(" Duck, Donald ")
'Donald Duck'
>>>
Use split() to separate the input at the commas. Strip spaces from each element to remove the extraneous spaces, and then reverse the list.
def reverse_names(string1):
names = string1.split(',') # split at commas
names = [name.strip() for name in names] # remove extra spaces
return " ".join(names[::-1]) # return reversed names as a string
you can use a regular expression to replace all the intermediate non-letter characters with a single space (then remove leading/trailing spaces). Then use a regular rsplit() to separate the first and last name (assuming that only the last name can be composite). Reassemble the inverted split result using join():
import re
def reverse_name(name):
name = re.sub('\W+',' ',name).strip()
return " ".join(name.rsplit(' ',1)[::-1])-1])
print(reverse_name("Techie, Teddy"))
print(reverse_name("Scumble, Arnold"))
print(reverse_name("von Grünbaumberger, Herbert"))
print(reverse_name("Fortunato,Frank"))
print(reverse_name("X,"))
print(reverse_name(",X"))
print(reverse_name(" , Y "))
print(reverse_name(" Duck, Donald "))
Teddy Techie
Arnold Scumble
Herbert von Grünbaumberger
Frank Fortunato
X
X
Y
Donald Duck
Of course, this leaves the problem of composite first names such as John-Paul Smith which creates an ambiguity on which words are part of the first and last name. If there is always going to be a comma, then the solution would be different (but you would have to state that explicitly in your question)
Solution based on systematic presence of a comma between last and first name:
def reverse_name(name):
names = re.sub('[^,\w]+',' ',name).split(',',1)
return " ".join(map(str.strip,names)).strip()

Confused about the type of parameter that goes into this method

I'm trying to understand how this code works, we have:
people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson',
'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']
def split_title_and_name(person):
return person.split()[0] + ' ' + person.split()[-1]
So we are given a list, and this method is supposed to basically delete everything in the middle between "Dr." and the last name. As far as I know, the split() function cannot be used for lists, but for strings. so person must be a string. However, we also add [0] and [-1] to person, which means we should be getting the first and last character of "person" but instead, we get first word and last word. I cannot make sense of this code! May you please help me understand?
Any help is greatly appreciated, thank you :)
The split function splits the string into a list of words. And then we select the first and last words to form the output.
>>> person = 'Dr. Christopher Brooks'
>>> person.split()
['Dr.', 'Christopher', 'Brooks']
>>> person.split()[0]
'Dr.'
>>> person.split()[-1]
'Brooks'
This is not a real answer, just adding this for clarification on how the function would be used, given a list of strings.
people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson',
'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']
def split_title_and_name(person: str):
return person.split()[0] + ' ' + person.split()[-1]
# This code does not actually run (I guess this might have been what you were trying)
# result = split_title_and_name(people)
# Using a for loop to print the result of running function over each list element
print('== With loop')
for person in people:
result = split_title_and_name(person)
print(result)
# Using a list comprehension to get the same results as above
print('== With list comprehension')
results = [split_title_and_name(person) for person in people]
print(results)
Python's split() method splits a string into a list. You can specify the separator, the default separator is any whitespace. So in your case, you didn't specify any separator and therefore this function will split the string person into ['Dr.', 'Christopher', 'Brooks'] and therefore [0] = 'Dr.' and [-1] = 'Brooks'.
The syntax for split() function is: string.split(separator, maxsplit), here both parameters are optional.
If you don't give any parameters, the default values for separator is any whitespace such as space, \t , \n , etc and maxsplit is -1 (meaning, all occurrences)
You can learn more about split() on https://www.w3schools.com/python/ref_string_split.asp

Keep the first X words in list elements whilst keeping the list one dimension?

I've a list which elements are comformed by words. In example:
listA = ["Hello, I'm Margaret and I'm 32 years old",
"Howdy, I'm Louis and I'm 35 years old",
"Greetings, I'm Veronica, I come from Canada",
"Night, I'm Pepe and I'm a mexican singer"]
However, I want to use a list comprehension to keep only the first three words of every element in the list, so the result is:
ListA = ["Hello, I'm Margaret",
"Howdy, I'm Louis",
"Greetings, I'm Veronica",
"Night, I'm Pepe"]
I've tried using the following list comprehension:
ListA = [i.split()[0:2] for i in ListA]
But this results in a list of lists, which is not desired:
ListA = [["Hello, I'm Margaret"],
["Howdy, I'm Louis"],
["Greetings, I'm Veronica"],
["Night, I'm Pepe"]]
Is using split() the correct approach? Thank you for your help!
You are almost there. Just make sure to join the string back:
ListA = [' '.join(e.split()[0:2]) for e in ListA]
Also you may want [0:3] and not [0:2], but that's up to you.
You just forgot to join the splitted list back to a string:
ListA = [' '.join(i.split()[0:2]) for i in ListA]

How to "properly" display a list in python without brackets

currently I am using
for s in list:
print(*s)
but it displays the list output as
['this is']
['the output']
But I would like the output to be displayed as
this is
the output
There should be a simple solution but i am still yet to come across one.
l = [['this is'], ['the output']]
for sub_list in l:
print(sub_list[0])
list_string = ', '.join(list_name)
print (list_string) #without brackets
Join using the newline character:
print("\n".join(your_list))
Please note that list is a Python type and shouldn't be used as a variable name.

How to split list elements to a line separated by space

I have a list in python as :
values = ['Maths\n', 'English\n', 'Hindi\n', 'Science\n', 'Physical_Edu\n', 'Accounts\n', '\n']
print("".join(values))
I want output should be as :-
Subjects: Maths English Hindi Science Physical_Edu Accounts
I am new to Python, I used join() method but unable to get expected output.
You could map the str.stripfunction to every element in the list and join them afterwards.
values = ['Maths\n', 'English\n', 'Hindi\n', 'Science\n', 'Physical_Edu\n', 'Accounts\n', '\n']
print("Subjects:", " ".join(map(str.strip, values)))
Using a regular expression approach:
import re
lst = ['Maths\n', 'English\n', 'Hindi\n', 'Science\n', 'Physical_Edu\n', 'Accounts\n', '\n']
rx = re.compile(r'.*')
print("Subjects: {}".format(" ".join(match.group(0) for item in lst for match in [rx.match(item)])))
# Subjects: Maths English Hindi Science Physical_Edu Accounts
But better use strip() (or even better: rstrip()) as provided in other answers like:
string = "Subjects: {}".format(" ".join(map(str.rstrip, lst)))
print(string)
strip() each element of the string and then join() with a space in between them.
a = ['Maths\n', 'English\n', 'Hindi\n', 'Science\n', 'Physical_Edu\n', 'Accounts\n', '\n']
print("Subjects: " +" ".join(map(lambda x:x.strip(), a)))
Output:
Subjects: Maths English Hindi Science Physical_Edu Accounts
As pointed out by #miindlek, you can also achieve the same thing, by using map(str.strip, a) in place of map(lambda x:x.strip(), a))
What you can do is use this example to strip the newlines and join them using:
joined_string = " ".join(stripped_array)

Categories

Resources