The_Redhawk
The_Redhawk

Reputation: 273

Removing extra space before an apostrophe in python

I was asked to write a program for a class that uses two lists. One list contains the names of 7 people (I used presidents' names), the other contains their 7 phone numbers. The goal of the program is for the user to enter the name of a friend and the program displays that friend's phone number. I have the program working just how I want it, but the output puts an extra space in it that I don't want.The output looks like this:

Your friend George Washington 's phone number is: 249-451-2869

I want to remove the space between "Washington" and "'s" so it reads more naturally. I tried different versions of strip() but could not get rid of the pesky space. Here is the main code for the program:

personName = nameGenerator() #function to allow user to enter name
nameIndex = IsNameInList(personName, Friends) #function that checks the user's input to see if input is #in the name list
print('Your friend',Friends[nameIndex],"\'s phone number is:",Phone_Numbers[nameIndex]) #Friends is name list, Phone_Numbers is numbers list, nameIndex stores the index of the proper name and phone number

Upvotes: 3

Views: 651

Answers (3)

ShadowRanger
ShadowRanger

Reputation: 155497

print adds spaces between arguments by default; pass sep='' (the empty string) to disable that. You'll need to add back spaces manually where you want them, but it's the minimal change:

print('Your friend ', Friends[nameIndex], "\'s phone number is: ", Phone_Numbers[nameIndex], sep='')

Alternatively, just use an f-string (or any other string formatting technique you prefer) to format it to a single string before printing:

print(f"Your friend {Friends[nameIndex]}'s phone number is: {Phone_Numbers[nameIndex]}")

Upvotes: 5

Nicolas Gervais
Nicolas Gervais

Reputation: 36664

You can just change the way you concatenate the strings. Instead of

print(string1, string2, string3)

You can concatenate them like this:

print(string1, string2 + string3)

In your case:

print('Your friend',Friends[nameIndex] + "\'s phone number is:",Phone_Numbers[nameIndex])

A + sign will not generate a space automatically, unlike using a ,.

Upvotes: 1

DenverCoder1
DenverCoder1

Reputation: 2501

When printing multiple, separate variables, Python automatically inserts spaces. You can use string concatenation instead to insert spaces only where you want.

personName = nameGenerator() #function to allow user to enter name
nameIndex = IsNameInList(personName, Friends) #function that checks the user's input to see if input is #in the name list
print('Your friend '+Friends[nameIndex]+"\'s phone number is: "+Phone_Numbers[nameIndex]) #Friends is name list, Phone_Numbers is numbers list, nameIndex stores the index of the proper name and phone number

Upvotes: 2

Related Questions