56.4k views
18 votes
Concentrate strings

Write code that concatenates the character strings in str1 and str2, separated by a space, and assigns the result to a variable named joined. Assume that both string variables have been initialized.
Two Letters in Word
Given a character string stored in a variable called word, write code that concatenates the fifth character of the word to the third character from the end of the word, and assigns that string to a variable named two_letters. Assume that word already has a value and is at least five characters long.
Set the Number of Cards if Necessary
Write code that sets the value of the variable num_cards to seven if its current value is less than seven. Otherwise, don't change the value. Assume that nuncards already has an initial value.

User Luthien
by
4.3k points

1 Answer

10 votes

Answer:

In Python:

(a) Concatenate strings:

joined = str1+" "+str2

(b) Two Letters in Word :

two_letters = word[4]+word[-3]

(c) Set Numbers in Card

if num_cards < 7:

num_cards = 7

Step-by-step explanation:

The code segments were written in Python

All variables were assumed to have been initialized

Solving (a): Concatenate strings:

To do this, we make use of + operator.

So, the concatenation of str1 and str2 with space in between is

str1+" "+str2

When assigned to variable joined, it becomes

joined = str1+" "+str2

Solving (b): Two Letters in Word :

The character at the 5th position is represented with index 4 i.e. word[4]

To access a character from the end, we make use of - sign. So, the third character from the end is word[-3]

Concatenate them using + operator.

So, we have:

two_letters = word[4]+word[-3]

Solving (c): Set Numbers in Card

Here, we make use of the if condtion.

First, check if num_cards is less than 7(i.e. num_cards < 7)

If true, assign num_cards to 7

So, we have:

if num_cards < 7:

num_cards = 7

User Sehafoc
by
4.0k points