


string a;
stack<char> b;
int main() {
IOS;
int t;
scanf("%d",&t);
while (t--) {
getline(cin,a);
int cnt=0;
for(int i=0;i<=a.size();i++)
{
if(a[i]==' '||a[i]=='.'||a[i]=='!'||a[i]=='?')
cnt++;
}
for (int i = 0, j = a.size() - 2; i < j;i++,j-- ) {
while (a[i] != ' '&&cnt>=1) {
cout << a[i];
i++;
}
cnt--;
if(cnt>=1)
cout << " ";
while (a[j] != ' '&&cnt>=1) {
b.push(a[j]);
j--;
}
cnt--;
while (!b.empty()) {
cout << b.top();
b.pop();
}
if(cnt>=1)
cout << " ";
}
cout << a[a.size()-1]<<endl;
}
return 0;
}