Suppose I have the following list:
temp = ['Ok', 'Whoa. Robot?']
How do I get a string that looks like
"1) 'Ok', 2) 'Whoa. Robot?'"
I'm trying to do this for a list comprehension. I can obviously join them using:
" ".join(temp)
I can do it in a loop in a fairly ugly way:
mystring = ""
temp = ['Ok', 'Whoa. Robot?']
for i in range(len(temp)):
mystring += str(i) + ") " + temp[i] + " "
Is there a pythonic way to do it in one step with a list comprehension?
mystring = ', '.join(["{}) {!r}".format(i, s) for i, s in enumerate(temp, 1)])
The {!r} conversion produces the repr() representation of the string, so you get quotes around the parts, but note that the quotes may change depending on the string's content, or in other words if it contains quotes itself.
Related
Hi I'am totally new to programmering and i have just jumped into it.
The problem i am trying to solve is to make a function that standardized an adress as input.
example:
def standardize_address(a):
numbers =[]
letters = []
a.replace('_', ' ')
for word in a.split():
if word. isdigit():
numbers. append(int(word))
elif word.isalpha():
letters.append(word)
s = f"{numbers} {letters}"
return s
Can someone help me explain my error and give me a "pro" programmers solution and "noob" (myself) solution?
This is what i should print:
a = 'New_York 10001'
s = standardize_address(a)
print(s)
and the output should be:
10001 New York
Right now my output is:
[10001] ['New', 'York']
Issues
strings are immutable so you need to keep the replace result, so do a = a.replace('_', ' ') or chain it before the split call
You need to concatenate the lists into one numbers + letters then join the elements with " ".join()
don't convert the numeric to int, that's useless and would force you to convert them back to str in the " ".join
def standardize_address(a):
numbers = []
letters = []
for word in a.replace('_', ' ').split():
if word.isdigit():
numbers.append(word)
elif word.isalpha():
letters.append(word)
return ' '.join(numbers + letters)
Improve
In fact you want to sort the words regarding the isdigit condition, so you can express that with a sort and the appropriate sorted
def standardize_address(value):
return ' '.join(sorted(value.replace('_', ' ').split(),
key=str.isdigit, reverse=True))
numbers and letters are both lists of strings, and if you format them they'll be rendered with []s and ''s appropriately. What you want to do is to replace this:
s = f"{numbers} {letters}"
return s
with this:
return ' '.join(numbers + letters)
numbers + letters is the combined list of number-strings and letter-strings, and ' '.join() takes that list and turns it into a string by putting ' ' between each item.
I am new to Python, and I am making a list. I want to make a print statement that says "Hello" to all the values in the lists all at once.
Objects=["Calculator", "Pencil", "Eraser"]
print("Hello " + Objects[0] + ", " + Objects[1] + ", " + Objects[2])
Above, I am repeating "Objects" and its index three times. Is there any way that I can simply write "Objects" followed by the positions of the values once but still get all three values printed at the same time?
Thanks
You could use join() here:
Objects = ["Calculator", "Pencil", "Eraser"]
print('Hello ' + ', '.join(Objects))
This prints:
Hello Calculator, Pencil, Eraser
You can use the string join function, which will take a list and join all the elements up with a specified separator:
", ".join(['a', 'b', 'c']) # gives "a, b, c"
You should also start to prefer f-strings in Python as it makes you code more succinct and "cleaner" (IMNSHO):
Objects = ["Calculator", "Pencil", "Eraser"]
print(f"Hello {', '.join(Objects)}")
Not sure this is the most elegant way but it works:
strTemp = ""
for i in range(len(Objects)):
strTemp += Objects[i] + " "
print ("Hello " + strTemp)
Start with an empty string, put all the values in your list in that string and then just print a the string Hello with your Temporary String like above.
So i have this code where i'm creating a list with substrings:
string = "|01|12345|TEXT1|TEXT2|"
x = string.count("|")
if string.count('|') == 3:
subst = string.strip('|').split('|')
print(substr)
else:
substr = string.strip('|').split('|')
print(substr)
Outcome:
['01', '12345', 'TEXT1', 'TEXT2']
However, i want to print all the substrings so that the outcome is this:
[LAS|01|G12345|TEXT1|TEXT2|]
I know i can just do:
print("[LAS|" + substr[0] + "|G" + substr[1] + "|" + substr[2] + "|" + substr[3])
But this is hardcoded, what if my the string that i get makes way more substrings? I do not want to use allot of if statements, if the count of ('|') == 4, == 5, == 6 etc.
How do i make sure that what i print contains all the substrings. And has a pipe symbol (|) in between every substring.
Thanks,
print("[LAS|%s|]" % "|".join(substr))
The "|".join(substr) takes all the pieces in substr and joins them with the | separator.
If you need the extra "G", you'll need to treat the first one or two elements separately:
print("[LAS|%s|G%s|]" % (substr[0], "|".join(substr[1:]))
or
print("[LAS|%s|G%s|%s|]" % (substr[0], substr[1], "|".join(substr[2:]))
string = '|01|12345|TEXT1|TEXT2|'
substr = string.strip('|').split('|')
if len(substr) != 3: # If you already have used split better to check the length than counting
substr.insert(0, '[LAS')
substr[2] = 'G' + substr[2]
substr.append("]")
print("|".join(substr)) # [LAS|01|G12345|TEXT1|TEXT2|]
What is the most efficient way to remove spaces from a text, and then after the neccessary function has been performed, re-insert the previously removed spacing?
Take this example below, here is a program for encoding a simple railfence cipher:
from string import ascii_lowercase
string = "Hello World Today"
string = string.replace(" ", "").lower()
print(string[::2] + string[1::2])
This outputs the following:
hlooltdyelwrdoa
This is because it must remove the spacing prior to encoding the text. However, if I now want to re-insert the spacing to make it:
hlool tdyel wrdoa
What is the most efficient way of doing this?
As mentioned by one of the other commenters, you need to record where the spaces came from then add them back in
from string import ascii_lowercase
string = "Hello World Today"
# Get list of spaces
spaces = [i for i,x in enumerate(string) if x == ' ']
string = string.replace(" ", "").lower()
# Set string with ciphered text
ciphered = (string[::2] + string[1::2])
# Reinsert spaces
for space in spaces:
ciphered = ciphered[:space] + ' ' + ciphered[space:]
print(ciphered)
You could use str.split to help you out. When you split on spaces, the lengths of the remaining segments will tell you where to split the processed string:
broken = string.split(' ')
sizes = list(map(len, broken))
You'll need the cumulative sum of the sizes:
from itertools import accumulate, chain
cs = accumulate(sizes)
Now you can reinstate the spaces:
processed = ''.join(broken).lower()
processed = processed[::2] + processed[1::2]
chunks = [processed[index:size] for index, size in zip(chain([0], cs), sizes)]
result = ' '.join(chunks)
This solution is not especially straightforward or efficient, but it does avoid explicit loops.
Using list and join operation,
random_string = "Hello World Today"
space_position = [pos for pos, char in enumerate(random_string) if char == ' ']
random_string = random_string.replace(" ", "").lower()
random_string = list(random_string[::2] + random_string[1::2])
for index in space_position:
random_string.insert(index, ' ')
random_string = ''.join(random_string)
print(random_string)
I think this might Help
string = "Hello World Today"
nonSpaceyString = string.replace(" ", "").lower()
randomString = nonSpaceyString[::2] + nonSpaceyString[1::2]
spaceSet = [i for i, x in enumerate(string) if x == " "]
for index in spaceSet:
randomString = randomString[:index] + " " + randomString[index:]
print(randomString)
string = "Hello World Today"
# getting index of ' '
index = [i for i in range(len(string)) if string[i]==' ']
# storing the non ' ' characters
data = [i for i in string.lower() if i!=' ']
# applying cipher code as mention in OP STATEMENT
result = data[::2]+data[1::2]
# inserting back the spaces in there position as they had in original string
for i in index:
result.insert(i, ' ')
# creating a string solution
solution = ''.join(result)
print(solution)
# output hlool tdyel wrdoa
You can make a new string with this small yet simple (kind of) code:
Note this doesn't use any libraries, which might make this slower, but less confusing.
def weird_string(string): # get input value
spaceless = ''.join([c for c in string if c != ' ']) # get spaceless version
skipped = spaceless[::2] + spaceless[1::2] # get new unique 'code'
result = list(skipped) # get list of one letter strings
for i in range(len(string)): # loop over strings
if string[i] == ' ': # if a space 'was' here
result.insert(i, ' ') # add the space back
# end for
s = ''.join(result) # join the results back
return s # return the result
When I run the code below I get:
Thank you for joining, ['cars', 'gas', 'jewelry']but['bus', 'join'] are not keywords.
How can I effectively turn the lists in to just strings to be printed? I suspect I may need a regular expression... this time :)
import re
pattern = re.compile('[a-z]+', re.IGNORECASE)
text = "join cars jewelry gas bus"
keywordset = set(('cars', 'jewelry', 'gas', 'food', 'van', 'party', 'shoes'))
words = pattern.findall(text.lower())
notkeywords = list(set(words) - keywordset)
keywords = list(keywordset & set(words))
if notkeywords == ['join']:
print "Thank you for joining keywords " + str(keywords) + "!"
else:
print "Thank you for joining, " + str(keywords) + "but" + str(notkeywords) + " are not keywords."
To convert list to strings use str.join like this
print "Thank you for joining keywords " + ",".join(keywords) + "!"
This if notkeywords == ['join']: is not a way to compare list elements.
>>> mylist = [1,2]
>>> mylist == 1
False
you should in operator to check for equality.
>>> mylist = [1,2]
>>> 1 in mylist
True
Just use someString.join(list):
if notkeywords == ['join']:
print "Thank you for joining keywords " + ", ".join(keywords) + "!"
else:
print "Thank you for joining, " + ", ".join(keywords) + "but" + ", ".join(notkeywords) + " are not keywords."
If I understood your question correctly, you'll want to use the .join() string method to combine the list before printing it.
For example:
', '.join(my_list)
will give you comma separated output. ', ' can be whatever kind of separator you like.