I have what I think is a basic question in Python:
I have a list that can be variable in length and I need to insert it into a string for later use.
Formatting is simple, I just need a comma between each name up to nameN and parenthesis surrounding the names.
List = ['name1', 'name2' .... 'nameN']
string = "Their Names are <(name1 ... nameN)> and they like candy.
Example:
List = ['tom', 'jerry', 'katie']
print(string)
Their Names are (tom, jerry, katie) and they like candy.
Any ideas on this? Thanks for the help!
# Create a comma-separated string with names
the_names = ', '.join(List) # 'tom, jerry, katie'
# Interpolate it into the "main" string
string = f"Their Names are ({the_names}) and they like candy."
There are numerous ways to achieve that.
You could use print + format + join similar to the example from #ForceBru.
Using format would make it compatible with both Python2 and Python3.
names_list = ['tom', 'jerry', 'katie']
"""
Convert the list into a string with .join (in this case we are separating with commas)
"""
names_string = ', '.join(names_list)
# names_string == "tom, katie, jerry"
# Now add one string inside the other:
string = "Their Names are ({}) and they like candy.".format(names_string)
print(string)
>> Their Names are (tom, jerry, katie) and they like candy.
Related
how may I be able to take from a string in python a value that is in a given text but is inside it, it's between 2 letters that I want it to copy from inside.
e.g.
"Kahoot : ID:1234567 Name:RandomUSERNAME"
I want it to receive the 1234567 and the RandomUSERNAME in 2 different variables.
a way I found to catch is to get it between the "ID:"COPYINPUT until the SPACE., "Name:"COPYINPUT until the end of the text.
How do I code this?
if I hadn't explained correctly tell me, I don't know how to ask/format this question! Sorry for any inconvenience!.
If the text always follows the same format you could just split the string. Alternatively, you could use regular expressions using the re library.
Using split:
string = "Kahoot : ID:1234567 Name:RandomUSERNAME"
string = string.split(" ")
id = string[2][3:]
name = string[3][5:]
print(id)
print(name)
Using re:
import re
string = "Kahoot : ID:1234567 Name:RandomUSERNAME"
id = re.search(r'(?<=ID:).*?(?=\s)', string).group(0)
name = re.search(r'(?<=Name:).*', string).group(0)
print(id)
print(name)
I am trying to create a string separated by comma from the below given list
['D:\\abc\\pqr\\123\\aaa.xlsx', 'D:\\abc\\pqr\\123\\bbb.xlsx', 'D:\\abc\\pqr\\123\\ccc.xlsx']
New string should contain only the filename like below which is separated by comma
'aaa.xlsx,bbb.xlsx,ccc.xlsx'
I have achieved this using the below code
n = []
for p in input_list:
l = p.split('\\')
l = l[len(l)-1]
n.append(l)
a = ','.join(n)
print(a)
But instead of using multiple lines of code i would like to achieve this in single line using a list comprehension or regular expression.
Thanks in advance...
Simply do a
main_list = ['D:\\abc\\pqr\\123\\aaa.xlsx', 'D:\\abc\\pqr\\123\\bbb.xlsx', 'D:\\abc\\pqr\\123\\ccc.xlsx']
print([x.split("\\")[-1] for x in main_list])
OUTPUT:
['aaa.xlsx', 'bbb.xlsx', 'ccc.xlsx']
In case u want to get the string of this simply do a
print(",".join([x.split("\\")[-1] for x in main_list]))
OUTPUT:
aaa.xlsx,bbb.xlsx,ccc.xlsx
Another way to do the same is:
print(",".join(map(lambda x : x.split("\\")[-1],main_list)))
OUTPUT:
aaa.xlsx,bbb.xlsx,ccc.xlsx
Do see that os.path.basename is OS-dependent and may create problems on cross-platform scripts.
Using os.path.basename with str.join
Ex:
import os
data = ['D:\\abc\\pqr\\123\\aaa.xlsx', 'D:\\abc\\pqr\\123\\bbb.xlsx', 'D:\\abc\\pqr\\123\\ccc.xlsx']
print(",".join(os.path.basename(i) for i in data))
Output:
aaa.xlsx,bbb.xlsx,ccc.xlsx
I'm a novice in python programming and i'm trying to split full name to first name and last name, can someone assist me on this ? so my example file is:
Sarah Simpson
I expect the output like this : Sarah,Simpson
You can use the split() function like so:
fullname=" Sarah Simpson"
fullname.split()
which will give you: ['Sarah', 'Simpson']
Building on that, you can do:
first=fullname.split()[0]
last=fullname.split()[-1]
print(first + ',' + last)
which would give you Sarah,Simpson with no spaces
This comes handly : nameparser 1.0.6 - https://pypi.org/project/nameparser/
>>> from nameparser import HumanName
>>> name = "Sarah Simpson"
>>> name = HumanName(name)
>>> name.last
'Simpson'
>>> name.first
'Sarah'
>>> name.last+', '+name.first
'Simpson, Sarah'
you can try the .split() function which returns a list of strings after splitting by a separator. In this case the separator is a space char.
first remove leading and trailing spaces using .strip() then split by the separator.
first_name, last_name=fullname.strip().split()
Strings in Python are immutable. Create a new String to get the desired output.
You can use split() method of string class.
name = "Sarah Simpson"
name.split()
split() by default splits on whitespace, and takes separator as parameter. It returns a list
["Sarah", "Simpson"]
Just concatenate the strings. For more reference https://docs.python.org/3.7/library/stdtypes.html?highlight=split#str.split
Output = "Sarah", "Simpson"
name = "Thomas Winter"
LastName = name.split()[1]
(note the parantheses on the function call split.)
split() creates a list where each element is from your original string, delimited by whitespace. You can now grab the second element using name.split()[1] or the last element using name.split()[-1]
split() is obviously the function to go for-
which can take a parameter or 0 parameter
fullname="Sarah Simpson"
ls=fullname.split()
ls=fullname.split(" ") #this will split by specified space
Extra Optional
And if you want the split name to be shown as a string delimited by coma, then you can use join() or replace
print(",".join(ls)) #outputs Sarah,Simpson
print(st.replace(" ",","))
Input: Sarah Simpson => suppose it is a string.
Then, to output: Sarah, Simpson. Do the following:
name_surname = "Sarah Simpson".split(" ")
to_output = name_surname[0] + ", " + name_surname[-1]
print(to_output)
The function split is executed on a string to split it by a specified argument passed to it. Then it outputs a list of all chars or words that were split.
In your case: the string is "Sarah Simpson", so, when you execute split with the argument " " -empty space- the output will be: ["Sarah", "Simpson"].
Now, to combine the names or to access any of them, you can right the name of the list with a square brackets containing the index of the desired word to return. For example: name_surname[0] will output "Sarah" since its index is 0 in the list.
I can't find a good example of the following in my textbook:
name = (input("Enter name(First Last:"))
last = name.split()
From here, I want to input the last name into another string.
How can I accomplish this task?
full_name = input("Enter name (First Last):")
first_name, last_name = full_name.split()
print(first_name)
print(last_name)
Split will return 2 strings here because full_name contains only one space between first and last name
After looking a little harder I figured out how input a variable into the middle of a string.
Here is the answer for i found for removing numbers from a string and inserting it to another string
<var0> = ''.join([i for i in <var1> if not i.isdigit()])
var0 = the string minus the numbers
var1 = the initial string to be changed
I'm creating a google searcher in python. Is there any way that I can replace a space in a list with a "+" for my url? This is my code so far:
q=input("Question=")
qlist=list(q)
#print(qlist)
Can I replace any spaces in my list with a plus, and then turn that back into a string?
Just want to add another line of thought there. Try the urllib library for parsing url strings.
Here's an example:
import urllib
## Create an empty dictionary to hold values (for questions and answers).
data = dict()
## Sample input
input = 'This is my question'
### Data key can be 'Question'
data['Question='] = input
### We'll pass that dictionary hrough the urlencode method
url_values = urllib.parse.urlencode(data)
### And print results
print(url_values)
#-------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------
#Alternatively, you can setup the dictionary a little better if you only have a couple of key-value pairs
## Input
input = 'This is my question'
# Our dictionary; We can set the input value as the value to the Question key
data = {
'Question=': input
}
print(urllib.parse.urlencode(data))
Output:
'Question%3D=This+is+my+question'
You can just join it together to create 1 long string.
qlist = my_string.split(" ")
result = "+".join(qlist)
print("Output string: {}".format(result))
Look at the join and split operations in python.
q = 'dog cat'
list_info = q.split()
https://docs.python.org/3/library/stdtypes.html#str.split
q = ['dog', 'cat']
s_info = ''.join(q)
https://docs.python.org/3/library/stdtypes.html#str.join