Swapping first and last names removing commas - python

Using python 3.3:
I need some help in writing the body for this function that swaps the positions of the last name and first name.
Essentially, I have to write a body to swap the first name from a string to the last name's positions.
The initial order is first name followed by last name (separated by a comma). Example: 'Albus Percival Wulfric Brian, Dumbledore'
The result I want is: 'Dumbledore Albus Percival Wulfric Brian'
My approach was:
name = 'Albus Percival Wulfric Brian, Dumbledore
name = name[name.find(',')+2:]+", "+name[:name.find(',')]
the answer I get is: 'Dumbledore, Albus Percival Wulfric Brian' (This isn't what I want)
There should be no commas in between.
I'm a new user to Python, so please don't go into too complex ways of solving this.
Thanks kindly for any help!

You can split a string on commas into a list of strings using syntax like astring.split(',')
You can join a list of strings into a single string on whitespace like ' '.join(alist).
You can reverse a list using list slice notation: alist[::-1]
You can strip surrounding white space from a string using astring.strip()
Thus:
' '.join(aname.split(',')[::-1]).strip()

You're adding the comma in yourself:
name = name[name.find(',')+2:] + ", " + name[:name.find(',')]
Make it:
name = name[name.find(',')+2:] + name[:name.find(',')]

Related

How can I print the first name? [duplicate]

This question already has answers here:
How do I split a string into a list of words?
(9 answers)
How to get first element in a list of tuples?
(17 answers)
Apply function to each element of a list
(4 answers)
Closed 7 months ago.
name = ['Marina Allison', 'Markus Valdez', 'Connie Ballard', 'Darnell Weber', 'Sylvie Charles', 'Vinay Padilla', 'Meredith Santiago', 'Andre Mccarty', 'Lorena Hodson', 'Isaac Vu']
# how can I get the first name for ex. Marina
Name is the list of random names.
I've tried joining it with .join()
Try in this way:
name = ['Marina Allison', 'Markus Valdez', 'Connie Ballard', 'Darnell Weber', 'Sylvie Charles', 'Vinay Padilla', 'Meredith Santiago', 'Andre Mccarty', 'Lorena Hodson', 'Isaac Vu']
for i in name:
print(i.split(' ')[0])
Your question is somewhat ambiguous, so I'll provide an answer for the interpretations I find most obvious.
Firstly, given a full-name string name = "First Last", I would recommend these approaches to getting just the First portion of the string:
Find the space and splice the string. This is arguably the most efficient method.
first_name = name[:name.find(" ")]
In Python, strings are character lists. name.find(" ") returns the index of the first occurrence of " ". Using this index, we splice the string and take only its characters preceding the space.
Split at the space and select the first element.
first_name = name.split()[0] # split at whitespace, take first element
split() with no specified input argument splits on all white space, including spaces, newlines, carriage returns, etc, and returns a list of the elements separated by each of these whitespace characters. This is less efficient than the first solution but more concise.
Now, to apply this on the entire name list to obtain a list of only the first names, I offer these two code snippets:
First, the more straightforward approach
first_names = []
for elem in name:
first_names.append(elem[:elem.find(" ")])
Next, using functional programming tools
first_names = list(map(lambda x: x[:x.find(" ")], name))
To print the result of either of these:
print("\n".join(first_names))
or
for x in first_names:
print(x)
Using list comprehension, one can get first name as list:
[x.split()[0] for x in name]
o/p:
['Marina',
'Markus',
'Connie',
'Darnell',
'Sylvie',
'Vinay',
'Meredith',
'Andre',
'Lorena',
'Isaac']

how to get second last and last value in a string after separator in python

In Python, how do you get the last and second last element in string ?
string "client_user_username_type_1234567"
expected output : "type_1234567"
Try this :
>>> s = "client_user_username_type_1234567"
>>> '_'.join(s.split('_')[-2:])
'type_1234567'
You can also use re.findall:
import re
s = "client_user_username_type_1234567"
result = re.findall('[a-zA-Z]+_\d+$', s)[0]
Output:
'type_1234567'
There's no set function that will do this for you, you have to use what Python gives you and for that I present:
split slice and join
"_".join("one_two_three".split("_")[-2:])
In steps:
Split the string by the common separator, "_"
s.split("_")
Slice the list so that you get the last two elements by using a negative index
s.split("_")[-2:]
Now you have a list composed of the last two elements, now you have to merge that list again so it's like the original string, with separator "_".
"_".join("one_two_three".split("_")[-2:])
That's pretty much it. Another way to investigate is through regex.

I want to replace a special character with a space

Here is the code i have until now :
dex = tree.xpath('//div[#class="cd-timeline-topic"]/text()')
names = filter(lambda n: n.strip(), dex)
table = str.maketrans(dict.fromkeys('?:,'))
for index, name in enumerate(dex, start = 0):
print('{}.{}'.format(index, name.strip().translate(table)))
The problem is that the output will print also strings with one special character "My name is/Richard". So what i need it's to replace that special character with a space and in the end the printing output will be "My name is Richard". Can anyone help me ?
Thanks!
Your call to dict.fromkeys() does not include the character / in its argument.
If you want to map all the special characters to None, just passing your list of special chars to dict.fromkeys() should be enough. If you want to replace them with a space, you could then iterate over the dict and set the value to for each key.
For example:
special_chars = "?:/"
special_char_dict = dict.fromkeys(special_chars)
for k in special_char_dict:
special_char_dict[k] = " "
You can do this by extending your translation table:
dex = ["My Name is/Richard????::,"]
table = str.maketrans({'?':None,':':None,',':None,'/':' '})
for index, name in enumerate(dex, start = 0):
print('{}.{}'.format(index, name.strip().translate(table)))
OUTPUT
0.My Name is Richard
You want to replace most special characters with None BUT forward slash with a space. You could use a different method to replace forward slashes as the other answers here do, or you could extend your translation table as above, mapping all the other special characters to None and forward slash to space. With this you could have a whole bunch of different replacements happen for different characters.
Alternatively you could use re.sub function following way:
import re
s = 'Te/st st?ri:ng,'
out = re.sub(r'\?|:|,|/',lambda x:' ' if x.group(0)=='/' else '',s)
print(out) #Te st string
Arguments meaning of re.sub is as follows: first one is pattern - it informs re.sub which substring to replace, ? needs to be escaped as otherwise it has special meaning there, | means: or, so re.sub will look for ? or : or , or /. Second argument is function which return character to be used in place of original substring: space for / and empty str for anything else. Third argument is string to be changed.
>>> a = "My name is/Richard"
>>> a.replace('/', ' ')
'My name is Richard'
To replace any character or sequence of characters from the string, you need to use `.replace()' method. So the solution to your answer is:
name.replace("/", " ")
here you can find details

Get rid of numbers from a string in python

I want to get names from a website in a list.
soup = bs4.BeautifulSoup(page.text, 'html.parser')
tbl = soup.find('ul', class_='static-top-names part1')
for link in tbl:
names = link.get_text()
print(names)
So i'm trying to get some names from a website and when i applied above code, i get names as a . When i try to iterate over it i get below output.
John
Mark
Steve and so on.
I want to get rid of the number in the text data and also just want to have the names in a list format.
All i want is to get these pure names and hopefully put them in a list form. Any help?
If the format is always #. name, then you can do the following:
name.split('. ', 1)[1]
Use regular expression for consistency.
import re
s = '1.TEST'
print(re.sub('\d+.','',s))
will give you TEST only. This will eliminate any size of number following with a dot. Basically, replace any number followed by a dot with emptiness.
Iterate over your original list and do the above at the same time using list comprehension
new_list = [re.sub('\d+.','',s) for s in original_list]
This should give you the new list as per your requirement.
You can simply split with '.' dot character or even a space if there is a space before name.
So name.split('' )[-1] name.split('.')[-1] would give just the name. Then you can append those names into a list.
Something like this.
names = [link.get_text().split(' ')[-1] for link in tbl]
This will you the list of just names, i used [-1] as the list index after since your text contains only two items after splitting with space. So if there are more items please use appropriate index.

Split according to ":" in multiple lines

I have a set of files composed as follows:
Product: Name
Description: description of product
I want to extract only the name and the description's content without the 'Product:' and 'Description:'. For this I do:
div = re.split('Product:\s+|Description:\s+', contentOfFile)
The problem is that I get a table of 3 elements instead of 2 with a ' ' (space) at the beginning. I don't know if space is always taken into account because I just want to get in this case:
["Name","description of product"]
Let's simplify your example. What if we split on pipe instead of your regular expressions?
>>> "|a|b".split('|')
['', 'a', 'b']
If the string starts with a separator, split will add an extra empty element in the returned value. Now in your case the separator is a regular expression, but similarly, your string begins with something that matches that expression, so the first returned element is an empty string.
To address it, you can just skip the first element
div = re.split('Product:\s+|Description:\s+', contentOfFile)[1:]
You don't need split, use findall:
>>> re.findall(r":\s+(.*)", a)
['Name', 'description of product']
Using this solution, you won't be dependent on the text before the :, so even when you have:
SomeText: Name
BlaBlaBla: description of product
it'll extract Name and description of product. It's a good practice to write general solution for your problem and try to think about possible future scenarios.
A general solution through split method without using regex.
>>> x = """Product: Name
Description: description of product"""
>>> [i.split(':')[1].lstrip() for i in x.split('\n')]
['Name', 'description of product']
i think you can try the strip function instead of split...
it aldo help to remove space..
here a small example of split function
str1 = "Product: Name";
str2 = "Description: description of product";
print str1.lstrip('Product:, ');
print str2.lstrip('Description:, ');
and the output shown as below....
Name
description of product

Categories

Resources