iterate through a tuple to form a string - python

I am trying to create a function named make_string, that uses * correctly with a parameter: strings
The function should return a string of all the values supplied joined, and separated by a space.
Outside the make_string function, I declare a variable named my_string, and assign the value returned from the make_string function.
Then I call the make_string function with the following values: "Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth". Finally I print the value of my_string to the terminal...and it returns None, when it should return Alderaan Coruscant Dagobah Endor Hoth
Can anybody tell me where I am going wrong please?
def make_string(*strings):
my_string = ""
for x in strings:
my_string = x.join(strings)
return my_string
my_string = make_string()
make_string("Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth")
print(my_string)

There are a few things going on in your code that are a little wonky.
You're constantly re-assigning the value of my_string every time you loop through for x in strings
There's no reason to start with a blank string here since you're already using join
Your function call isn't setting to my_string -- it isn't set to anything. What you want is like my_string = make_string("Bob", "Mary") etc.
This should do the trick:
def make_string(*strings):
return " ".join(strings)
my_string = make_string("Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth")
print(my_string)
Personally, I would say you don't even need a function here, especially if you can easily set what you're using for *strings to a variable. For example:
planets = ["Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth"]
print(" ".join(planets))

Related

How can i define a function that reads and returns all values in the list using Python?

I have this string delimited by commas.
'1.0,5.0,6.0,7.0,8.0,9.0'
def var():
for i in listnumbers:
return i +'.0'
When I do
var()
I only get
1.0
How do i get the result to include all the numbers in a loop?
1.0,5.0,6.0,7.0,8.0,9.0
def myfun(mycsv):
return [i+'.0' for i in mycsv.split(',')]
print(myfun('1.0,5.0,6.0,7.0,8.0,9.0'))
#['1.0.0', '5.0.0', '6.0.0', '7.0.0', '8.0.0', '9.0.0']
If you want a string, then just use join:
print(','.join(myfun('1.0,5.0,6.0,7.0,8.0,9.0')))
Or change the function to return a string;
return ','.join([i+'.0' for i in mycsv.split(',')])
You are returning inside the for loop, before the cycle is completed.
If I understood correctly your question, it looks like what you're looking for is list comprehension.
If your input is a list:
def var(l):
return [i + '.0' for i in l]
If your input is a string, like it seems from your description, you have to split it first:
def var(l):
return [i + '.0' for i in l.split(',')]
This is equivalent to mapping in other languages.
You can divide your string in a list using string.split(',') the you iterate over the freshly created list and print each element. A the code can be arranged like this:
for s in string.split(','):
print(s+'.0')

Function Not Printing Desired Output

I am having issues with creating a function that takes a list of tuples and then returns one string which is the first character of each tuple. Below is my current code, but nothing it happening, I do not get a syntax error. Any help would be appreciated.
lst_of_tups = ([('hello', 'all'), ('music', 'playing'), ('celebration', 'station')])
def build_string(lst_of_tups):
final_str = ""
for tup in list_of_tups:
for item in tup:
final_str = final_str + item[0]
return final_str
print build_string
**** expected output: hampcs****
those string manipulation functions are error-prone: they define lots of variables, can return within inner loops, have unexpected side-effects...
Once you're used to list comprehensions, you can create such programs easily & with great execution performance (string concatenation is slow). One way:
def build_string(lst_of_tups):
return "".join([x[0] for y in lst_of_tups for x in y])
basically, it's just 2 loops (flattening the data) within a list comprehension to extract each first character from every string, joined together using str.join to rebuild the string.
Once you reach a return statement in a function, the function ends for good. The line
print build_string
cannot be reached. (Another problem is that the name build_string is not defined.)
Use your function like this:
result = build_string(lst_of_tups) # calls your function and puts the return value in the result variable
print result # print the result
Of course, the intermediary variable result is not necessary, you could just issue print build_string(lst_of_tups) as well.

Reversing string in python using def

Can anyone help me with the assignment - I have to reverse a string by using def. I am not allowed to use approaches like [::-1] or .reversed...
The following function works, but prints vertically:
def ex1(name):
for x in range(len(name)-1,-1,-1):
print(name[x])
k
r
o
Y
w
e
N
how do I put the letters back into horizontal order?? Anyone? Thanks!
You can use str.join and a list comprehension like so:
>>> def ex1(name):
... return "".join([name[x] for x in range(len(name)-1,-1,-1)])
...
>>> print(ex1('abcd'))
dcba
>>>
Also, notice that I made the function return the string instead of print it. If your teachers want you to use def for this job, then they probably want that too. If not, then you can always replace return with print if you want.
You were very close:
def ex1(name):
reverseName=""
for x in range(len(name)-1,-1,-1):
reverseName+=name[x]
print reverseName
The print statement prints a newline character (a line break) after each line, this is why you get your characters in vertical. The solution is not to print the character in each loop, but to collect them in a string and print the final string at once at the end.
Note that there are more efficient ways of doing this (see the other answers), but it might be the most straightforward way and the closest one to what you have already done.
Here is another way that you can reverse a string.
def ex1(name):
length = len(name)
return "".join([name[length-x-1] for x in range(0, length)])
print ex1("hello world")
name=input("Whats your name ?")
def reversemyname(name):
x=name[::-1]
return x
reversedname=reversemyname(name)
print(reversedname)
print(name[x]), # <= add that comma
if you want the output like this kroy wen then try this:
sys.stdout.write(name[x])
remember to import sys

If one or more letters equals the same as a variable; Python

I have some code:
multi = "testtest"
if(type[0] == multi[0]):
print("test")
But then if I run it, it works, but if I type t, the 1st letter, and then some other letters:
tfdsajfdsaf, it won't print test. Is there any other way I could make this work if the other letters are different?
Sounds like you might want to use startswith(), which is a part of the string class.
if string_name.startswith(multi[0]):
print 'test'
You can also use slices:
if string_name.startswith(multi[:3]):
print 'test'

Python string manipulation without comparison

I am trying to solve this problem: I have some symbols:
list =["RBS-UK", "GOOG-US"]
Now I have to transform all the region occurrences of "UK" to "GB". I could have done this easily:
new_list =[]
for symbol in list :
temp_list=symbol.split("-")
if temp_list[1]=="UK":
temp_list[1]="GB"
new_list.append("-".join(temp_list))
But can I do this without the equality comparision?
I am looking for something along the lines of:
some_dict={}
new_list =[]
for symbol in list :
temp_list=symbol.split("-")
temp_list[1]=some_dict(temp_list[1]) # So this dict returns GB if its UK else returns same value as it is
new_list.append("-".join(temp_list))
Is it possible to do this, or are there any other solutions?
Yeah! sure
ls =['RBS-UK','GOOG-US']
map(lambda x: x.replace('-UK', '-GB'), ls)
You are looking for a lookup, for which a dictionary will work:
translations = {'UK':'GB'} # and so on
for symbol in lst:
country_code = symbol.split('-')[1]
translated = translations.get(country_code,country_code)
new_list.append('{}-{}'.format(symbol.split('-')[0],translated))
The key line is:
translated = translations.get(country_code,country_code)
Dictionary have a method get() which will return None if the key is not found. We use this to avoid raising KeyError. get() takes an optional second parameter for a value to return other than None if the key is not found.
In the snippet above, we pass the country code to get(), and ask it to return the same country code if there isn't a translation available, otherwise return the translation.
The second line uses string formatting to reconstruct the original symbol with the translated code and appends it to your list.
You don't actually have to redefine the offset. You can simply replace the string:
for symbol in list:
symbol = symbol.replace('-UK','-GB')
If the string is encountered it will be replaced, otherwise it is left alone entirely.
If you really want to use a dict, you could use the dict.get method, which accepts a default argument used when the key isn't found, and so some_dict.get(x,x) means "return the value associated with x if it exists, otherwise return x":
>>> some_dict = {"UK": "GB"}
>>> country = "UK"
>>> some_dict.get(country, country)
'GB'
>>> country = "CA"
>>> some_dict.get(country, country)
'CA'
You can use the sub function from the re module useful for regular expression operations.
Here is a one-liner which produces the list you want:
import re
newlist = [re.sub('UK','GB', symbol) for symbol in list]

Categories