List within a string and print formatting - python

I am creating something which takes a tuple, converts it into a string and then reorganises the string using print formatting. 'other' can sometimes have 2 names, hence why I have used * and the " ".join(other) in this function:
def strFormat(x):
#Convert to string
s=' '
s = s.join(x)
print(s)
#Split string into different parts
payR, dep, sal, *other, surn = s.split()
payR, dep, sal, " ".join(other), surn
#Print formatting!
print (surn , other, payR, dep, sal)
The problem with this is that it prints a list of 'other' within the string like this:
Jones ['David', 'Peter'] 84921 Python 63120
But I want it more like this:
Jones David Peter 84921 Python 63120
So that it is ready for formatting into something like this:
Jones, David Peter 84921 Python £63120
Am I going about this the right way and how do I stop the list appearing within the string?

You're close. Change this line (which does nothing):
payR, dep, sal, " ".join(other), surn
to
other = " ".join(other)

Related

How to print a string which is a name with two words in reverse order without commas and unnecessary spaces? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have to write a function that takes a string of full names and prints it in reverse order. It also removes unnecessary spaces and commas. Some of the expected output is as follow:
- >>> reverse_name("Techie, Teddy")
'Teddy Techie'
>>> reverse_name("Scumble, Arnold")
'Arnold Scumble'
>>> reverse_name("Fortunato,Frank")
'Frank Fortunato'
>>> reverse_name("von Grünbaumberger, Herbert")
'Herbert von Grünbaumberger'
>>> reverse_name(" Duck, Donald ")
'Donald Duck'
>>> reverse_name("X,")
'X'
>>> reverse_name(",X")
'X'
>>> reverse_name(" , Y ")
'Y'.
I wrote the following code.
def main():
name=input()
reverse_name(name)
print(reverse_name(name))
def reverse_name(string1):
i = 0
for index in string1:
if index != ",":
i += 1
else:
last = string1[i + 1:]
first = string1[0:i]
result = last + " " + first
return result
if __name__ == "__main__":
main()
p.s: I must implement a function that takes a string as a parameter and returns a string. The input will also contain a comma which the output will not print.
You could combine split and join after having inverted the output of split:
def reverse_name(s):
return ' '.join([e.strip() for e in s.split(', ')][::-1])
>>> reverse_name('Techie, Teddy')
'Teddy Techie'
>>> reverse_name(' Duck, Donald ')
'Donald Duck'
Here is another option using the re module:
def reverse_name(s):
return re.sub(r'\s*(.+),\s*(.*\S)\s*', r'\2 \1', s)
if a comma is guaranty to always be there simply using string1.split(",") will give you a list of the separate words in the string, and simple filter the empty one and removing the trailing white spaces with .strip will do the trick
>>> def reverse_name(text):
return " ".join( w for w in map(str.strip,reversed(text.split(","))) if w)
# ^removing trailing white space ^filter empty ones
>>> reverse_name("Techie, Teddy")
'Teddy Techie'
>>> reverse_name("Scumble, Arnold")
'Arnold Scumble'
>>> reverse_name("von Grünbaumberger, Herbert")
'Herbert von Grünbaumberger'
>>> reverse_name("Fortunato,Frank")
'Frank Fortunato'
>>> reverse_name("X,")
'X'
>>> reverse_name(",X")
'X'
>>> reverse_name(" , Y ")
'Y'
>>> reverse_name(" Duck, Donald ")
'Donald Duck'
>>>
Use split() to separate the input at the commas. Strip spaces from each element to remove the extraneous spaces, and then reverse the list.
def reverse_names(string1):
names = string1.split(',') # split at commas
names = [name.strip() for name in names] # remove extra spaces
return " ".join(names[::-1]) # return reversed names as a string
you can use a regular expression to replace all the intermediate non-letter characters with a single space (then remove leading/trailing spaces). Then use a regular rsplit() to separate the first and last name (assuming that only the last name can be composite). Reassemble the inverted split result using join():
import re
def reverse_name(name):
name = re.sub('\W+',' ',name).strip()
return " ".join(name.rsplit(' ',1)[::-1])-1])
print(reverse_name("Techie, Teddy"))
print(reverse_name("Scumble, Arnold"))
print(reverse_name("von Grünbaumberger, Herbert"))
print(reverse_name("Fortunato,Frank"))
print(reverse_name("X,"))
print(reverse_name(",X"))
print(reverse_name(" , Y "))
print(reverse_name(" Duck, Donald "))
Teddy Techie
Arnold Scumble
Herbert von Grünbaumberger
Frank Fortunato
X
X
Y
Donald Duck
Of course, this leaves the problem of composite first names such as John-Paul Smith which creates an ambiguity on which words are part of the first and last name. If there is always going to be a comma, then the solution would be different (but you would have to state that explicitly in your question)
Solution based on systematic presence of a comma between last and first name:
def reverse_name(name):
names = re.sub('[^,\w]+',' ',name).split(',',1)
return " ".join(map(str.strip,names)).strip()

Confused about the type of parameter that goes into this method

I'm trying to understand how this code works, we have:
people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson',
'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']
def split_title_and_name(person):
return person.split()[0] + ' ' + person.split()[-1]
So we are given a list, and this method is supposed to basically delete everything in the middle between "Dr." and the last name. As far as I know, the split() function cannot be used for lists, but for strings. so person must be a string. However, we also add [0] and [-1] to person, which means we should be getting the first and last character of "person" but instead, we get first word and last word. I cannot make sense of this code! May you please help me understand?
Any help is greatly appreciated, thank you :)
The split function splits the string into a list of words. And then we select the first and last words to form the output.
>>> person = 'Dr. Christopher Brooks'
>>> person.split()
['Dr.', 'Christopher', 'Brooks']
>>> person.split()[0]
'Dr.'
>>> person.split()[-1]
'Brooks'
This is not a real answer, just adding this for clarification on how the function would be used, given a list of strings.
people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson',
'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']
def split_title_and_name(person: str):
return person.split()[0] + ' ' + person.split()[-1]
# This code does not actually run (I guess this might have been what you were trying)
# result = split_title_and_name(people)
# Using a for loop to print the result of running function over each list element
print('== With loop')
for person in people:
result = split_title_and_name(person)
print(result)
# Using a list comprehension to get the same results as above
print('== With list comprehension')
results = [split_title_and_name(person) for person in people]
print(results)
Python's split() method splits a string into a list. You can specify the separator, the default separator is any whitespace. So in your case, you didn't specify any separator and therefore this function will split the string person into ['Dr.', 'Christopher', 'Brooks'] and therefore [0] = 'Dr.' and [-1] = 'Brooks'.
The syntax for split() function is: string.split(separator, maxsplit), here both parameters are optional.
If you don't give any parameters, the default values for separator is any whitespace such as space, \t , \n , etc and maxsplit is -1 (meaning, all occurrences)
You can learn more about split() on https://www.w3schools.com/python/ref_string_split.asp

Extracting specific string after specific character

new = ['mary 2jay 3ken +', 'mary 2jay 3ken +', 'steven +john ']
print(new):
mary 2jay 3ken +
mary 2jay 3ken +
steven +john -
How could I get the sign/number after each person's name? I'm wondering whether dict would work in this case as my expected output is:
mary:2
jay:3
ken:+
steven:+
john:-
To get the index of "+" in a string, you can use:
index = a_string.index("+")
To check if "+" exist in a string, use:
if "+" in a_string:
# ...
To iterate a list of string, you can do:
for text in new:
# ...
There are fifty ways to do what you want. I suggest you to read the Python tutorial.
edit
You can use a RegEx to extract the fields name/number
for text in next:
couples = re.findall(r"(\S+)\s+(\d+|\+|\-|$)", text)
for name, num in couples:
print(name, num)

SQL / Python - String replacement pattern with commas

I need to achieve the following task using preferably SQL string functions (i.e CHARINDEX, LEFT, TRIM, etc) or Python.
Here's the problem:
Example string: BOB 3A, ALICE 6M
Required output: 3aB, 6mA
As you can see I need to get the last two characters for each word preceding a comma, then append the first character of each item to the end. Preferably this should work for any number of items with commas separating them but the likely case is two.
Any hints / direction would be great. Thanks.
Here's a Python solution:
def thesplit(s):
result = []
for each in s.split(', '):
name, chars = each.split(' ')
result.append(chars.lower() + name[0])
return ', '.join(result)
You can use it like this: thesplit('BOB 3A, ALICE 6M')
Yoyu may try this,
>>> s = "number: 123456789"
>>> ', '.join([i[-2]+i[-1].lower()+i[0] for i in s.split(', ')])
'3aB, 6mA'
Try this:
str = 'BOB 3A, ALICE 6M'
print ', '.join( map( lambda x: x[-2:].lower()+x[0], str.split(", ") ) )

Python: Formatting a list (which contains a list) for printing

I'm working on a project that translates input to Pig Latin (yeah, I'm sure you've never seen this one before...) and having trouble formatting my output.
(for the following, sentence = a list holding user input (phrase), split by phrase.split() )
sentence.remove(split)
final = map(str,sentence)
print "Final is (before formatting:", final
final = [sentence[0].capitalize()] , sentence[1:]
#finalFormat = ' '.join(final)
print "Final is", str(final).strip('[]')
#print "FinalFormat is", finalFormat
print "In Pig Latin, you said \"", ' '.join(map(str, final)), "\". Oink oink!"
What I get is:
"In Pig Latin, you said "['Firstword'] ['secondword', 'thirdword'] "
What I am looking for is:
"In Pig Latin, you said "Firstword secondword thirdword."
Based on my debug print statements it looks like my problem is still on the line (5 from the bottom):
final = [sentence[0].capitalize()] , sentence[1:]
Thanks in advance!
Change this line:
final = sentence[0].capitalize() , sentence[1:]
To this:
final = [sentence[0].capitalize()] + sentence[1:]
You were mapping a tuple of a string and a list, to strings, rather than a list.
Note: using 'single"' quotes here will avoid "this\"" ugliness.

Categories

Resources