How can I print the first name? [duplicate] - python

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']

Related

Split string into list by separate delimiters, but only by certain instances of said delimiters [duplicate]

This question already has answers here:
Split string with multiple delimiters in Python [duplicate]
(5 answers)
Closed 2 years ago.
I think what I'm trying to achieve is fairly common but I can't find reference for it on the internet; either that or I'm misphrasing what I'm trying to do.
This is the string I would like to split:
array_1:target:radec, 0:00:00.00, -90:00:00.0
I would like to split it by the first two colons (':'), and by the first comma & space (', '), such that I get
['array_1', 'target', 'radec', '0:00:00.00, -90:00:00.0']
I've tried to run split() with arguments twice on the original string, and it fails on the second split() because I'm trying to split something that's already a list. All the other answers I can find seem to focus on splitting the string by all instances of a delimiter, but I want the last field in the list 0:00:00.00, -90:00:00.0 to remain like it is.
First split it by the first ", " (using maxsplit=1), then the first element of the resulting list split by ":":
s = "array_1:target:radec, 0:00:00.00, -90:00:00.0"
temp = s.split(", ", maxsplit=1)
temp[0] = temp[0].split(":")
result = temp[0] + [temp[1]]
The result:
['array_1', 'target', 'radec', '0:00:00.00, -90:00:00.0']
How about
l1 = s.split()
l2 = l1[0].split(':') + l1[1:]
This will first split by whitespace separator, then split the first element (only) by a colon separator, and then join the lists. Result:
['array_1', 'target', 'radec,', '0:00:00.00,', '-90:00:00.0']

How do I print one word at a time from a list I got from user input? [duplicate]

This question already has answers here:
Python split string into multiple string [duplicate]
(3 answers)
Closed 2 years ago.
I ask for a user to input names and I need to return them one a time from a list, but what happens is only single letters are returned instead of the full name.
Names = input("Enter names here: ")
The list I get is something like this,
Jim, John, Sarah, Mark
This is what I try,
print (Names[0])
What I get as a return
J
I want Jim as the return a nothing else.
When input reads the data it will return a string, which you must break into a list. Thankfully strings have a method split just for that. Try:
Names = input("Enter names here: ")
Names = Names.split(',')
You can split the string on spaces or comma and other common delimiters using a simple regular expression. That gives you an array of strings, in case, the words.
Then you chose the first element of the array.
line="Jim, John, Sarah, Mark"
words = re.split(r'[;,\s]\s*', line)
print (words[0])
"Names" variable stores the input as a string. Convert it into a list using:
names_list = Names.split(', ')
print(names_list[0])
However, this will only work if you enter names separated by a comma followed by a space.
A better way is to create an empty list first and then append input elements to the list. Following is an example:
# Creating an empty list
names_list = []
# Iterates till the input is empty or none
while True:
inp = input("Enter name: ")
if inp == "":
break
names_list.append(inp)
# Prints first element of the list
print(names_list[0])

How to split strings by only the first special character that's within the string? [duplicate]

This question already has answers here:
Splitting on first occurrence
(5 answers)
Closed 8 years ago.
I'd like to split the below string by only the first equal sign in that string
String:
s= 'ButtonParams=U3ViamVjdCxFbWFpbA=='
Desired_String:
s= ['ButtonParams','U3ViamVjdCxFbWFpbA==']
When I do s.split("="), I get the following, which is what I do not want:
s.split("=")
['ButtonParams', 'U3ViamVjdCxFbWFpbA', '', '']
I need to run this function across a list of strings where this is the case, so scalability is important here.
split accepts an optional "maxsplit" parameter: if you set it to 1 it will split on the first = character it finds and return the remainder of the string:
>>> s.split('=', 1)
['ButtonParams', 'U3ViamVjdCxFbWFpbA==']
s.split("=", maxsplit=1) is the best but
import re
print (re.split('=',s,1))
The output is
['ButtonParams', 'U3ViamVjdCxFbWFpbA==']
As you have tagged regex
A little deviation from the post
If the expected output was ['ButtonParams', 'U3ViamVjdCxFbWFpbA'] then you can have the following liscos (list comprehensions)
[i for i in s.split('=') if i is not '']
[i for i in s.split('=') if i ] (Contributed by Adam Smith)
str.split accepts an optional argument maxsplit which determines how many splits (maximally) to make, e.g.:
"ButtonParams=U3ViamVjdCxFbWFpbA==".split("=", maxsplit=1)
# ['ButtonParams', 'U3ViamVjdCxFbWFpbA==']

Swapping first and last names removing commas

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(',')]

Select last chars of string until whitespace in Python [duplicate]

This question already has answers here:
Python: Cut off the last word of a sentence?
(10 answers)
Closed 8 years ago.
Is there any efficient way to select the last characters of a string until there's a whitespace in Python?
For example I have the following string:
str = 'Hello my name is John'
I want to return 'John'. But if the str was:
str = 'Hello my name is Sally'
I want to retrun 'Sally'
Just split the string on whitespace, and get the last element of the array. Or use rsplit() to start splitting from end:
>>> st = 'Hello my name is John'
>>> st.rsplit(' ', 1)
['Hello my name is', 'John']
>>>
>>> st.rsplit(' ', 1)[1]
'John'
The 2nd argument specifies the number of split to do. Since you just want last element, we just need to split once.
As specified in comments, you can just pass None as 1st argument, in which case the default delimiter which is whitespace will be used:
>>> st.rsplit(None, 1)[-1]
'John'
Using -1 as index is safe, in case there is no whitespace in your string.
It really depends what you mean by efficient, but the simplest (efficient use of programmer time) way I can think of is:
str.split()[-1]
This fails for empty strings, so you'll want to check that.
I think this is what you want:
str[str.rfind(' ')+1:]
this creates a substring from str starting at the character after the right-most-found-space, and up until the last character.
This works for all strings - empty or otherwise (unless it's not a string object, e.g. a None object would throw an error)

Categories

Resources