I need help to see what is wrong with my code; I'm getting the incorrect output.
I need the output to print the first initial and last name (with a period . in front of the first initial), for example: "Anna Lockswell" should be printed as "A. Lockswell".
So far I have:
firstName = input("What is your first name? ")
lastName = input("What is your last name? ")
str(print(firstname[0:-1], +lastname))
Welcome to programming! There are a few issues with what you've posted. First, let's try to get the first letter of firstname:
firstname = input("What is your first name? ")
# firstname is a string, where each letter acts like an element in an array
# to get the first letter, do this:
first_initial = firstname[0]
Per Micha's suggestion, the reason I'm using firstname[0] is because I only want the first letter. The slice firstname[0:-1] will give you everything except the last letter, which isn't quite what you want.
Now, you already have your lastName, next to print.
You have str(print("thing to print")). The problem here is print is a function which doesn't return anything. By wrapping that in str you will see the output None. To print, just call print:
print(first_initial + '.' + ' ' + lastName)
You will need to add a space to the printed output to space out the initial and the last name. There are fancier and more pythonic ways to print, but I feel that this is a sufficient place to start
here are a few things that need attention:
when you write firstname[a:b] it'll return the value of
firstname from char a to char b. so when your firstname is
"anna" and you'll type firstname[1:3] you'll get 'nn'. in this case minus one is equal to the index of the last character which is 3. so firstname[0:-1] will return "ann". in your case it should be changed to firstname[0].
str in the last line is completely unnecessary. str is used for converting other types to string. for example str(1) returns '1'.
print(a,b) will print 2 3 assuming a = 2 and b = 3 so you'll need to use print( a + '.' + b) for getting 2.3. ( there are many other ways to do this).
Try any of these:
>>> print('{}. {}'.format(firstname[0], lastname))
A. Lockswell
>>> print(firstname[0] + '. ' + lastname)
A. Lockswell
>>> print(f'{firstname[0]}. {lastname}')
A. Lockswell
Related
Please write a program which asks the user to type in a string. The program then prints out all the substrings which begin with the first character, from the shortest to the longest. Have a look at the example below.
Please type in a string: test
t
te
tes
test
Obviously my code is not the way it supposed to be:
stg = input("Please type in a string: ")
print(stg[0])
print(stg[0:5])
print(stg[0:10])
print(stg[10:50])
print(stg[:])
ok, this is a homework and I don't give you the exact solution... but as some points:
you have a string and want to print first 1 letter, first 2 letters and so on... so your range end must increase one by one...
you don't know about input length so you can't use hard code and use a loop
for loop you need to know about string length and use a builtin method for getting the length...
any question? ask it...
userString = input("Gimme String: ")
# Looping based on the given String
# Last Value is not included so you need to increment the value by one
for i in range(len(userString)):
# Last Value is not included so you need to increment the value by one
print(userString[:i+1])
#Alternative
for i in range(1,len(userString)+1):
print(userString[:i])
stg = input("Please type in a string: ")
print("\n".join([stg[0:i+1] for i in range (len(stg))]))
Output:
t
te
tes
test
Just use simple for loop
stg = 'test'
temp_str = ''
for i in range(len(stg)):
temp_str = temp_str + stg[i]
print(temp_str)
I'm currently struggling to separate a string into two while using a white space as the base of the split.
I'm writing a program where a person is supposed to input their first and last name as a string. Then the program should take the first three letters out of the first name and first three letters out of the last name. Put these together and append them to a domain name creating an email. Such as Firstname Lastname becomes firlas#example.com. I know I could easily solve the problem by just using two inputs, but I want it to be only one input.
def create_email_address():
name = input("Please input your first and last name: ")
domain = "#aperturescience.com"
email_address = str.lower(name[:3]) + str.lower(name[10:13]) + domain
print(str(email_address))
This is what I have so far, and while I have experimented using list splits and indexes I can't get it to work properly. I can get the index to work when I use my own name as an example name. But if I input something that doesn't have the same amount of characters in it it doesn't perform as I want it to.
What I would like is to separate the first name and last name using the white space as the indicator where the split is supposed to be. That way it won't matter how long or short the names are, I can always index after the first three letters in each name.
Is this possible? and if so, any tips?
Thanks!
def create_email_address():
name = input("Please input your first and last name: ")
domain = "#aperturescience.com"
names=name.split()
email_address = str.lower(names[0][:3]) + str.lower(names[1][:3]) + domain
print(str(email_address))
The above code has been slightly modified to use split - which will create a list from your input string assuming that it is delimited by whitespaces.
Use str.split() method to get the first and last name. Note: if you don't specify attributes, it will split not only by space, but by all the space characters (e.g. "\n" - new line)
Here are the parts of your code which should be corrected:
1) It's better to use name[:3].lower() instead str.lower(name[:3]), though the code works fine in both cases. In Python, we almost always call method of a class from an already created instance (str_instance.lower() instead of str.lower(str_instance)
2) You shouldn't use print(str(...)), because print will convert the result to string even if you don't specify it explicitly. Moreover, in this case it is already a string.
So, here is the full fixed code:
first, last = input("Please input your first and last name: ").split()
domain = "#aperturescience.com"
email_address = first[:3].lower() + last[:3].lower() + domain
print(email_address)
You can use str.split() like so:
# get user input:
full_name = input('Enter your full name: ')
# split user input on white space, this will return a list:
first_name = full_name.split()[0]
last_name = full_name.split()[1]
# get first three characters in string:
first_name_first_three = first_name[0:3]
last_name_first_three = last_name[0:3]
print(first_name_first_three)
print(last_name_first_three)
One of the best ways to do that would be to use regular expressions. Please refer to the examples below.
import re
pattern = re.compile('\W+')
name = "Jerry Maguire"
split_names = pattern.split(name)
split_names
Out[24]: ['Jerry', 'Maguire']
name = "FrodoBaggins"
split_names = pattern.split(name)
split_names
Out[27]: ['FrodoBaggins']
This would handle scenarios where there are no spaces or if name needs to be split on multiple lines.
While we're all giving solutions, I'll just give you the bad answer. A one liner:
>>> print("".join(["".join([i[:3].lower() for i in input("Enter your full name: ").split(" ")]), "#example.com"]))
Enter your full name: Albert Finksson
albfin#example.com
This one is almost unreadable though, for your sake and others in the future use the other solutions.
I see that the use case where name contains more than two word (e.g. middle name) hasn't been addressed. So here's my attempt to answer,
def create_email():
name = input("Enter Full Name : ")
domain = "example.com"
email = name[:3].lower() + name.split()[-1][:3].lower() + "#" + domain
print(email)
Couple of pointers on the code above:
you don't really need to split to get the first three letters of first name as it's just the first three letters of full name
name.split()[-1] will get the last name from full name and [:3] will get the first three letters of last name
I need to create a program for my python instructor that processes a name and outputs it in the format "Last, First". The 2 different ways the user can input their name are, "first last"(no comma), or "last, first".
I've used my Python book but it does not help much when it comes to what the instructor wants from us to create.
space = name.index(' ')
first = name[0:1].upper()+name[1:space]
comma = name.index(',')
last = name[0:1].upper()+name[1:comma]
print(last + ', ' + first)
The correct result of this program should be "Last, First" as I stated already above. I keep getting the first name entered and the output is "name, name," (name is whatever is being inputted into the input statement)
example.) user input --> 'joe bob'
output --> 'Joe, Joe,'
The mistake you did was first and last were assigned the same string.
I would suggest doing something like this:
name = 'Bob, joe'
if ',' in name:
last, first = name.split(',')
else:
first, last = name.split(' ')
print(last.strip().capitalize() + ', ' + first.strip().capitalize())
Hope this helps.
You can do something like this:
name = input("Write a name: ")
space_idx = name.index(' ')
if "," in name:
print(name)
else:
name = name[space_idx+1:] + ", " + name[:space_idx]
print(name)
In Python3, you can use the split() method to convert a string into a list of words, separated by spaces.
This can be done by words = name.split().
Now, assuming that you have already learned string manipulation, you can remove the comma from the end of the first name (if there is), the first word in the words list.
Then, simply print the list for first name and last name.
Good luck!
So the simplest way is to user rstrip and split function
getting the value in list and print it from index number
name = list(map(str, input().rstrip().split()))
print(name[1], name[0])
print(name[1] + ', '+ name[0])
Input
Firstname Lastname
OutPut
Lastname Firstname
lastname, Firstname
My current code
defname,last_name):
if not isinstance(reg, int) or \
not isinstance(year, int) or \
not isinstance(degree, str) or \
not isinstance(other_name, str) or \
not isinstance(last_name, str) :
print("Invalid string argument")
elif 0<=year<=4:
l.append((reg,year,degree,other_name,last_name))
else: print("Invalid year")
def p
reg,year,degree,other_name,last_name = student.strip().split(" ",4)
reg=int(reg)
year=int(year)
fullName=last_name+ ", " + other_name
thisYear="Year " + str(year)
print(format(fullName, "<32s")+format(reg,"<7d")+format(degree,">6s"),format(thisYear,">6s"))
how can I do this effectively with the right formats? I am trying to make it so it uses both functions and is checking for valid
Well, for the reason it's printing on that side, that's because of the way you called .split(). Calling it with the 4 will of course restrict it to splitting 4 times. And since it splits from left to right, once it has made its 4th split (ie. after 'Homer'), it will simply return the rest of the string as a whole (ie. 'J Simpson').
If I were you, I would do it like this:
reg,year,degree,*name = student.strip().split(" ")
name = list(reversed(name))
fullname = name[0] + ', ' + ' '.join(name[1:])
Doing *name lets you grab multiple tokens as a list, and then process them however you like.
First off, wouldn't you want it to print Simpson, Homer J?
Secondly, it prints it J Simpson, Homer because this is what your list looks like:[1342347, 2, G401, Homer, J Simpson].
It splits it this way because you told it to split at each space it sees, and to make a maximum of 4 separate strings. It doesn't know that middle names belong to other_name, so you have to do a little more work in your string parsing to get that to behave as desired.
This is because you are limiting the number of splits to 4.
Thus, for the third line, the 4th space that gets split is between "Homer" and "J". Thus, "J" and "Homer" are in the same string after the split.
https://www.tutorialspoint.com/python/string_split.htm
I'm sure this is covered in plenty of places, but I don't know the exact name of the action I'm trying to do so I can't really look it up. I've been reading an official Python book for 30 minutes trying to find out how to do this.
Problem: I need to put a string in a certain length "field".
For example, if the name field was 15 characters long, and my name was John, I would get "John" followed by 11 spaces to create the 15 character field.
I need this to work for any string put in for the variable "name".
I know it will likely be some form of formatting, but I can't find the exact way to do this. Help would be appreciated.
This is super simple with format:
>>> a = "John"
>>> "{:<15}".format(a)
'John '
You can use the ljust method on strings.
>>> name = 'John'
>>> name.ljust(15)
'John '
Note that if the name is longer than 15 characters, ljust won't truncate it. If you want to end up with exactly 15 characters, you can slice the resulting string:
>>> name.ljust(15)[:15]
If you have python version 3.6 or higher you can use f strings
>>> string = "John"
>>> f"{string:<15}"
'John '
Or if you'd like it to the left
>>> f"{string:>15}"
' John'
Centered
>>> f"{string:^15}"
' John '
For more variations, feel free to check out the docs: https://docs.python.org/3/library/string.html#format-string-syntax
You can use rjust and ljust functions to add specific characters before or after a string to reach a specific length.
The first parameter those methods is the total character number after transforming the string.
Right justified (add to the left)
numStr = '69'
numStr = numStr.rjust(5, '*')
The result is ***69
Left justified (add to the right)
And for the left:
numStr = '69'
numStr = numStr.ljust(3, '#')
The result will be 69#
Fill with Leading Zeros
Also to add zeros you can simply use:
numstr.zfill(8)
Which gives you 00000069 as the result.
string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces
This will add the number of spaces needed, provided the field has length >= the length of the name provided
name = "John" // your variable
result = (name+" ")[:15] # this adds 15 spaces to the "name"
# but cuts it at 15 characters
I know this is a bit of an old question, but I've ended up making my own little class for it.
Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:
2021-03-02 update: Improved a bit - when working through a large codebase, you know whether the line you are writing is one you care about or not, but you don't know what was previously written to the console and whether you want to retain it.
This update takes care of that, a class variable you update when writing to the console keeps track of whether the line you are currently writing is one you want to keep, or allow overwriting later on.
class consolePrinter():
'''
Class to write to the console
Objective is to make it easy to write to console, with user able to
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------
#Class variables
stringLen = 0
overwriteLine = False
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteThisLine=False):
import sys
#Get length of stringIn and update stringLen if needed
if len(stringIn) > consolePrinter.stringLen:
consolePrinter.stringLen = len(stringIn)+1
ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
prevOverwriteLine = consolePrinter.overwriteLine
if prevOverwriteLine:
#Previous line entry can be overwritten, so do so
sys.stdout.write("\r" + ctrlString.format(stringIn))
else:
#Previous line entry cannot be overwritten, take a new line
sys.stdout.write("\n" + stringIn)
sys.stdout.flush()
#Update the class variable for prevOverwriteLine
consolePrinter.overwriteLine = overwriteThisLine
return
Which then is called via:
consolePrinter.writeline("text here", True)
If you want this line to be overwriteable
consolePrinter.writeline("text here",False)
if you don't.
Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.
I generally recommend the f-string/format version, but sometimes you have a tuple, need, or want to use printf-style instead. I did this time and decided to use this:
>>> res = (1280, 720)
>>> '%04sx%04s' % res
'1280x 720'
Thought it was a touch more readable than the format version:
>>> f'{res[0]:>4}x{res[1]:>4}'
First check to see if the string's length needs to be shortened, then add spaces until it is as long as the field length.
fieldLength = 15
string1 = string1[0:15] # If it needs to be shortened, shorten it
while len(string1) < fieldLength:
rand += " "
Just whipped this up for my problem, it just adds a space until the length of string is more than the min_length you give it.
def format_string(str, min_length):
while len(str) < min_length:
str += " "
return str